function MinePublishServiceController(analyseId){
	this.serviceDialog = null;
	this.service = {};
	var serviceObject = this.service;
	var dataSourceCache = {};


	/**
	 * 运行服务
	 */
	var runService = function(service){
		$.ajax({
			url : contextPath + '/api/ai/mine/publish/runService',
			type : 'post',
			data : {id : Service.id},
			success : function(obj) {
				if (obj) {
					console.log(obj);
				}
			}
		});
	}

	var deleteService = function(service){
		$("<div/>").confirm({
			title :  TempoUtils.locale("mine.publish-btn-delete"), 
			msg :  TempoUtils.locale("mine.publish-mine-job-grid-col-delete-confirm"),
			height : 160,
			width : 220,
			ok : function(){
				var process = $("<div/>").tempoprogressbar();
				$.ajax({
					url : contextPath + '/api/ai/mine/publish/deleteService',
					type : 'post',
					data : {id : service.id},
					success : function(obj) {
						debugger
						process.tempoprogressbar("destroy");
						$('#mine-opt-service-grid').jqGrid().trigger("reloadGrid");
					}
				});
			}
		});
	}
	
	/**
	 * 下载同步服务运行时环境jar依赖包
	 */
	var downloadRuntime = function() {
		TempoUtils.download({
			url: contextPath + "/api/ai/mine/sync/downloadRuntimeJars",
			data : {}
		});
	}

	var editService = function(service){
		var that = this;
		that.service = service;
		newService.apply(that, [service,true]);
	}

	/**
	 * 新增服务
	 */
	var newService = function(service, isEdit){
		var that = this;
		that.serviceDialog = $('#tempo-mine-flow-service-dialog').clone().appendTo('body');
		that.serviceDialog.dialog({
			width : 650,
			minHeight: 400,
			autoOpen : false,
			title: TempoUtils.locale('mine.publish-mine-service-dialog-title'),
			modal:true,
			resizable: false,
			close:function(){
				that.serviceDialog.dialog("destroy");
			},
			buttons:[{
				text: TempoUtils.locale('mine.publish-dialog-sure'),
				click:function(){
					saveServiceConfig.apply(that, [service, isEdit]);
				}
			},{
				text:TempoUtils.locale('mine.publish-dialog-cancel'),
				click:function(){
					that.serviceDialog.dialog("destroy");
				}
			}]
		});
		that.serviceDialog.dialog('open');
		initServiceLayout.apply(that, isEdit ? [service] : null);
		nameValid(that.serviceDialog.find('form').find("input[name='name']"));
	}

	/**
	 * 初始化表单数据
	 */
	var initFormData = function(service){
		var that = this;
		var dialog = that.serviceDialog;

		if(!service){
			service = {};
		}
		dialog.find('input[name="name"]').val(service.name).validatebox({validator: true, required: true});
	}

	var getRecord = function(){
		this.service.name = this.serviceDialog.find('input[name="name"]').val();
		this.service.themeId = analyseId;
		this.service.flowid = this.serviceDialog.find('select[name="flow"]').val();
	}


	/**
	 * 保存服务信息
	 */
	var saveServiceConfig = function(oldService, isEdit, callback){
		
		var that = this;
		if(!validateForm(this.serviceDialog)){
			return;
		}
		//暂存流程参数
		saveFlowParam.apply(that);
		getRecord.apply(that);
		if(!that.service.flowid){
			$("<div/>").alert({msg : TempoUtils.locale("mine.publish-job-none"), height : 180});
			return;
		}
		var url = isEdit ? contextPath + '/api/ai/mine/publish/editService' : contextPath + '/api/ai/mine/publish/saveService';
		var process = $("<div/>").tempoprogressbar();
		$.ajax({
			url : url,
			type : 'post',
			data : JSON.stringify(that.service),
			contentType : 'application/json',
			success : function(obj) {
				process.tempoprogressbar("destroy");
				if(callback) callback(obj);
				if(!oldService || !oldService.ignore) {
					if (obj && obj.status) {
							$('#mine-opt-service-grid').jqGrid().trigger("reloadGrid");
							that.serviceDialog.dialog("destroy");
					} else {
						$("<div/>").alert({msg : TempoUtils.locale("mine.publish-savefailed") + obj.error, height : 180, width: 400});
					}
				}
			}
		});
	}
	this.saveServiceConfig = saveServiceConfig;
	/**
	 * 暂存流程参数
	 */
	var saveFlowParam = function(){
		var that = this;
		var paramsTable = that.serviceDialog.find('#serviceParamGrid');
		var currentFlowParams = []
		var paramsLine = paramsTable.find('tbody tr');
		paramsLine.each(function(i){
			var paramName = $(this).find('input.flow_paramname').val();
			var paramValue = $(this).find('select.flow_paramvalue').selectmenu('getValue');
			var paramType = $(this).find('input.flow_paramtype').val();
			var paramId = $(this).find('input.flow_paramid').val();
			// 获取参数说明的值
			var paramDesc = $(this).find('input.flow_paramdesc').val();
			var param = {};
			param.paramName = paramName;
			param.paramValue = paramValue;
			param.paramId = paramId;
			param.paramType = paramType;
			// 保存参数说明
			param.paramDesc = paramDesc;
			if(!$.isEmptyObject(param)){
				currentFlowParams.push(param);
			}
		});
		this.service.flowParams = JSON.stringify(currentFlowParams);
	}

	/**
	 * 新增服务对话框
	 */
	var initServiceLayout = function(service){
		var that = this;
		var dialog = that.serviceDialog;
		initFormData.apply(that, [service]);
		initSelectFlowTable.apply(that, service? [service] : null);
	}




	var initSelectFlowTable = function(service){
		var that = this;
		var dialog = that.serviceDialog;
		var flows = $('#mine-published-grid').jqGrid('getRowData');
		//初始化流程选择下拉框
		var html = '';
		if(flows && flows.length > 0){
			for (var i = 0; i < flows.length; i++) {
				var flow = flows[i];
				var name = flow.name;
				var id = flow.id;
				html += '<option value="' + id + '">' + name + '</option>';
			}
		}
		dialog.find('select[name="flow"]').html(html).selectmenu({
			select : function(){
				flowSelectHandler.apply(that,[dialog.find('select[name="flow"]')])
			}
		});
		if(service && service.flowid){
			dialog.find('select[name="flow"]').val(service.flowid).selectmenu('refresh').selectmenu('disable');
		}
		flowSelectHandler.apply(that, [dialog.find('select[name="flow"]')]);
	}
	
	var getFlowParams = function(type, paramValueInput, value, nodeType,enable){
		var pss = [];
		if(type == 'datasource'){
			var loadDatasource = function(data) {
				for(var i =0;i<data.length;i++){
					var dataItem = data[i];
					// 屏蔽模型数据源、presto数据源、impala数据源
					if (nodeType == 'readrdbms') {
						if (!dataItem.type || TempoMineUtils.inputSupportType.indexOf(dataItem.type) == -1) {
							continue;
						}
					}
					if (nodeType == 'writerdbms') {
						if (!dataItem.type || TempoMineUtils.inputSupportType.indexOf(dataItem.type) == -1 || (dataItem.purpose && dataItem.purpose != "1")) {
							continue;
						}
					}

					if (nodeType == 'readhive') {
						if (dataItem.type != 'hive') {
							continue;
						}
					}
					if(nodeType == 'writehive'){
						if('hive' != dataItem.type  || (dataItem.purpose && dataItem.purpose != "1")){
							continue;
						}
					}
					if (nodeType == "readinfluxdb") {
						if (!(dataItem.type == "influxdb" || dataItem.type == "influxdb2")) {
							continue;
						}
					}
					if( nodeType == "readiotdb"){
						if (dataItem.type != 'iotdb') {
							continue;
						}
					}
					if( nodeType == "writeiotdb"){
						//不是iotdb  或者不能写入
						if ('iotdb' != dataItem.type  || (dataItem.purpose && dataItem.purpose != "1")) {
							continue;
						}
					}
					
					pss.push('<option value="' + dataItem.code + '">' + dataItem.name + '</option>')
				}
				var html = pss.join('');
				paramValueInput.html(html);
				paramValueInput.selectmenu({
					editable : false,
					width : 180
				}).selectmenu('setValue', value).selectmenu('refresh');
				if(enable == false){
					paramValueInput.selectmenu("option","disabled",true);
				}
			}
			if(dataSourceCache['datasource']) {
				loadDatasource(dataSourceCache['datasource']);
			} else {
				var process = $("<div/>").tempoprogressbar();
				$.ajax({
					url:contextPath + '/api/ai/node/io/list-datasources',
					type:'post',
					success:function(data) {
						process.tempoprogressbar("destroy");
						if(data.success) {
							dataSourceCache['datasource'] = data.data;
							loadDatasource(dataSourceCache['datasource']);
						} else {
							console.error("数据源加载失败");
						}
					}
				});
			}
		}else{
			var items = TempoMineUtils.getConstFlowParams();
			if(items){
				for(name in items){
					pss.push('<option value="' + name + '">' + items[name] + '</option>')
				}
			}
			var html = pss.join('');
			paramValueInput.html(html);
			paramValueInput.selectmenu({
				editable : true,
				width : 180
			}).selectmenu('setValue', value);
			if(enable == false){
				paramValueInput.selectmenu("option","disabled",true);
			}
		}

	}

	/**
	 * 流程选择事件处理
	 */
	var flowSelectHandler = function(target, isFirst, callback){
		var that = this;
		var dialog = that.serviceDialog;
		dialog.find('#flowParamsContainer').hide();
		var flowid = $(target).val();
		if(!flowid) return;
		var params = null;
		if(flowid == that.service.flowid){
			params = JSON.parse(that.service.flowParams);
		}
		if(params){
			params.forEach(function(v,i,a){delete a[i]});
			params = params.filter(function(v){if(v != null) return v});
		}
		var grid = dialog.find('#serviceParamGrid').attr('flowId', $(target).val());
		grid.find('tbody').empty();
		var initParamGrid = function(ps){
			dialog.find('#serviceParamGrid').show();
			for (var i = 0; i < ps.length; i++) {
				// 屏蔽系统参数
				if ('system.appId' == ps[i].paramName) {
					continue;
				}
				var tr = $('<tr>').appendTo(grid);
				var p = ps[i];
				var paramName = p.paramName;
				var paramValue = p.paramValue;
				var paramType = p.paramType;
				var paramId = p.paramId;
				var nodeType = p.nodeType;
				// 获取流程参数说明，兼容一下，以前没有置为空
				var paramDesc = "";
				if (p.paramDesc) {
					paramDesc = p.paramDesc;
				}
				var paramNameTd = $('<td>').appendTo(tr);
				var paramTypeInput = $('<input name="paramType" type="hidden">').addClass('flow_paramtype').appendTo(paramNameTd).val(paramType);
				var paramTypeInput = $('<input name="paramId" type="hidden">').addClass('flow_paramid').appendTo(paramNameTd).val(paramId);
				var paramNameInput = $('<input name="paramName">').addClass('flow_paramname').appendTo(paramNameTd).val(paramName).attr('title', paramName);
				paramNameInput.validatebox({width : 200, readonly : true, disabled: 'disabled'});
				var paramValueTd = $('<td>').appendTo(tr);
				var paramValueInput = $('<select name="paramValue">').addClass('flow_paramvalue').appendTo(paramValueTd);
				// 添加参数说明表格
				var paramDescTd = $('<td>').appendTo(tr);
				var paramDescInput = $('<input name="paramDesc">').addClass('flow_paramdesc').appendTo(paramDescTd).val(paramDesc).attr('title', paramDesc);
				paramDescInput.validatebox({width : 200, readonly : true, disabled: 'disabled'});


				paramNameInput.attr('title', paramName);
				getFlowParams(paramType, paramValueInput, paramValue, nodeType);
				// 参数说明 值回显
				paramDescInput.attr('title', paramDesc);
			}
		};
		if(!params || params.length == 0){
			$.ajax({
				url : contextPath+"/api/ai/mine/publish/getPublishFlowParams/" + flowid,
				type : 'post',
				success : function(result){
					if(result && result.length > 0){
						initParamGrid(result);
					}
					if(callback) callback(result);
				}
			})
		}else{
			initParamGrid(params);
		}
	}
	
	this.flowSelectHandler = flowSelectHandler;
	/**
	 * 服务列表事件
	 */
	var bindServiceGridEvent = function(){
		var that = this;
		var grid = $('#mine-opt-service-grid');

		grid.find(".viewlog").each(function(){
			var rowid = $(this).attr('rowid');
			var row = null;
			var rows = grid.data('rows');
			if(rows && rows.length > 0){
				for (var m = 0; m < rows.length; m++) {
					if(rowid == rows[m].id){
						row = rows[m];
					}
				}
			}
			var logs = row.logs;
			var content;
			if(logs && logs.length > 0){
				var logele = $('<ul>').css({
					'list-style-type' : 'none'
				});
				for (var i = 0; i < logs.length; i++) {
					var log = logs[i];
					var date = new Date(parseFloat(log.runTime));
					var runResult = log.runResult;
					var icon = "ui-icon ui-icon-document";
					if (runResult != null) {
						if (runResult == 0) {
							icon = "ui-icon tempo-ui-icon tempo-ui-icon-no-mutual tempo-ui-icon-red-circle-errorprompt";
						} else if (runResult == 1) {
							icon = "ui-icon tempo-ui-icon tempo-ui-icon-no-mutual tempo-ui-icon-red-circle-check-thin";
						}
					}
					var logName = DateUtils.formatDateTime(date, 'yyyy-MM-dd HH:mm:ss')
					var liele = $('<li class="logitem">').attr('logid', log.id).attr('runResult', runResult).attr('name', logName);
					var liicon = $("<span>").addClass(icon).appendTo(liele);
					var lilabel = $("<label>").text(logName).appendTo(liele);
					logele.append(liele);
				}
				content = $('<div>').append(logele).html();
			}
			$(this).webuiPopover({
				trigger : 'hover',
				title : '',
				cache : false,
				placement : 'right',
				width : 180,
				closeable : false,
				arrow : true,
				content : content
			})
			$(this).on('shown.webui.popover', function(){
				$('.logitem').each(function(index, domEle){
					$(domEle).off('click').on('click',function(){
						var logid = $(this).attr('logid');
						var runResult = $(this).attr('runResult');
						var name = $(this).attr('name');
						downloadLog(logid, name, runResult);
					})
				});
			});
		});
		
		grid.find('.downloadSynclog').click(function() {
			var rowid = $(this).attr('rowid');
			TempoUtils.downLoadFile({
				url: contextPath + "/api/ai/mine/sync/downloadonlinelog/" + rowid,
				data : {}
			});
		});
	}

	/**
	 * 下载任务日志
	 */
	var downloadLog = function(id, name,runResult){
		TempoUtils.downLoadFile({
			url: contextPath + "/api/ai/mine/publish/downloadServiceLog",
			data : {
				id : id,
				name : name,
				runResult : runResult
			}
		});
	}

	/**
	 * 初始化服务列表
	 */
	this.initServiceGrid = function() {
		var that = this;
		var height = $('#publish-mine-config').height()-155;
		var width = $('#publish-mine-config').width()-30;
		var GridListener = (function() {
			var len = 0;
			var refresh = function() {
				
				$.post(contextPath + '/api/ai/mine/publish/listService?time=' + new Date().getTime(),
						{
							themeId : analyseId,
							sord: 'asc',
							page: 1,
							rows: 100
						}, 
						function(data) {
							var rows = data.rows;
							serviceObject.rows = rows;
							var frow = rows.filter(function(e){ 
								return  (e.type == 'sync' || e.type == 'stream') 
									&& (e.launchState == 'STARTING') 
							});
							len = frow.length;
							if(frow.length && len > 0) {
								setTimeout(refresh, 1000);
							} 
							if(frow.length == 0 || len == 0 || len != frow.length) {
								that.grid.jqGrid().trigger("reloadGrid");
							}
				});
			}
			var start = function(rows) {
				if(len > 0) return ;
				len = rows.length;
				if(len > 0) setTimeout(refresh, 500);
			};
			return {
				start: start
			};
		})();
		
		that.grid = $('#mine-opt-service-grid').datagrid({
			datatype : "json",
			url : contextPath + '/api/ai/mine/publish/listService?time=' + new Date().getTime(),
			postData : {themeId : analyseId},
			height : height,
			width : width,
			fit:true,
			rownumbers : true,
			mtype : 'POST',
			autowidth:true,
			rownumbers : true,
			shrinkToFit : true, 
			viewrecords : true,
			striped : true,
			colNames : [ 'id', 
			             TempoUtils.locale("mine.publish-mine-service-name-label"),//'服务名称'
			             TempoUtils.locale("mine.publish-mine-service-grid-col-type"),//服务类型
			             TempoUtils.locale("mine.publish-mine-job-grid-col-creator"),//'创建者'
			             TempoUtils.locale("mine.publish-mine-service-grid-col-relatedflow"),//'涉及流程'
			             TempoUtils.locale("mine.qidongzhuangtai"),
			             TempoUtils.locale("mine.publish-mine-service-grid-col-authstatus"),//'授权状态'
			             TempoUtils.locale("mine.publish-mine-service-grid-col-log"),//'日志'
			             TempoUtils.locale("mine.publish-mine-service-grid-col-status"),//'运行状态'
			             TempoUtils.locale("mine.publish-mine-service-grid-col-opt")
			             ],//'操作'
			             colModel : [{
			            	 name : 'id',
			            	 index : 'id',
			            	 //hidden : true,
							 sortable : false,
			             },{
			            	 name : 'name',
			            	 index : 'name'
			             },
			             {
			            	name: 'type',
			            	index: 'type',
			            	width : 40,
			            	align : 'center',
			            	formatter : function(obj, grid, rows, state) {
			            		return obj == 'sync' ? TempoUtils.locale("mine.tongbu") : obj == 'stream' ? TempoUtils.locale("mine.liu") : TempoUtils.locale("mine.yibu");
			            	}
			             },
			             {
			            	 name : 'creatorName',
			            	 index : 'creatorName'
			             },{
			            	 name : '',
			            	 index : '',
			            	 formatter : function(obj, grid, rows, state) {
			            		 var fid = rows.flowid;
			            		 var flows = $('#mine-published-grid').jqGrid('getRowData');
			            		 if(flows && flows.length > 0){
			            			 for (var i = 0; i < flows.length; i++) {
			            				 var flow = flows[i];
			            				 var name = flow.name;
			            				 var id = flow.id;
			            				 if(id == fid){
			            					 return name;
			            				 }
			            			 }
			            		 }
			            		 return '';
			            	 }
			             },{
			            	 name : 'launchState',
			            	 index : 'launchState',
			            	 sortable : false,
			            	 width : 50, 
			            	 align : "center",
			            	 formatter : function(obj, grid, rows, state) {
			            		 if((rows.type == 'sync' || rows.type == 'stream') && obj == 'RUNNING') {
			            			 return TempoUtils.locale("mine.yiqidong");
			            		 } else if((rows.type == 'sync' || rows.type == 'stream') && (obj == 'STARTING')) {
			            			 return TempoUtils.locale("mine.zhengzaiqidong");
			            		 } else if((rows.type == 'sync' || rows.type == 'stream') && (obj == 'NONE' || !obj)) {
			            			 return TempoUtils.locale("mine.weiqidong");
			            		 } else {
			            			 return "--";
			            		 }
			            	 }
			             },{
			            	 name : '',
			            	 index : '',
			            	 sortable : false,
			            	 width : 120, 
			            	 align : "center",
			            	 formatter : function(obj, grid, rows, state) {
			            		 var success = rows.auth;
			            		 var type = rows.type;
			            		 if (type == "stream") {
			            			 return "--";
			            		 }
			            		 return  success ? TempoUtils.locale("mine.publish-mine-service-authed") : TempoUtils.locale("mine.publish-mine-service-noauthed");
			            	 }
			             },{
			            	 name : '',
			            	 index : '',
			            	 sortable : false,
			            	 align : 'left',
			            	 width : 40,
			            	 formatter : function(obj, grid, rows, state) {
			            		 var logs = rows.logs;
			            		 if(logs && logs.length > 0 && rows.type == 'async'){
			            			 return "<a href='javascript:;void(0)' rowid='" + rows.id + "' class='viewlog'>"+TempoUtils.locale("mine.publish-published-flow-grid-optview")+"</a>";
			            		 }
			            		 if(rows.resultType == 'EXECUTE') {
			            			 return "<a href='javascript:;void(0)' rowid='" + rows.id + "' class='downloadSynclog'>"+TempoUtils.locale("mine.xiazai")+"</a>";
			            		 }
			            		 return '';
			            	 }
			             },{
			            	 name : '',
			            	 index : '',
			            	 sortable : false,
			            	 width : 120, 
			            	 formatter : function(obj, grid, rows, state) {
			            		 var success = rows.successCount || 0;
			            		 var fail = rows.failedCount || 0;
			            		 return  TempoUtils.locale("mine.publish-mine-job-exe-success") +"<span style='color:green'>" + success + "</span>" +TempoUtils.locale("mine.publish-mine-job-exe-time")+ "　" + TempoUtils.locale("mine.publish-mine-job-exe-fail") + "<span style='color:red'>" + fail + "</span>" +TempoUtils.locale("mine.publish-mine-job-exe-time");
			            	 }
			             },{
			            	 name : '',
			            	 index : '',
			            	 sortable : false,
			            	 width : 100,
			            	 align : 'center',
			            	 buttons:[{
			            		 id : "operate",
			            		 icon:"ui-icon tempo-ui-icon tempo-ui-icon-launch",
			            		 title: TempoUtils.locale("mine.fuwukaiguan"),
			            		 beforeAdd : function(rowId,rowData, btn){
			            			 if(rowData.launchState == 'RUNNING' || rowData.launchState == 'STARTING') {
			            				 btn.icon = 'ui-icon tempo-ui-icon tempo-ui-icon-msstop';
			            			 } else {
			            				 btn.icon = 'ui-icon tempo-ui-icon tempo-ui-icon-launch';
			            			 }
			            			 return (rowData.type == 'sync' || rowData.type == 'stream');
			            		 },
			            		 click:function(e,dt){
			            			 var row = dt.rowData;
			            			 operateOfSetting.apply(that, [e, dt]);
			            		 }
			            	 },{
			            		 id : "edit",
			            		 icon:"ui-icon tempo-ui-icon tempo-ui-icon-edit",
			            		 title: TempoUtils.locale("mine.publish-btn-edit"),
			            		 beforeAdd : function(rowId,rowData, btn){
			            			 return !rowData.auth;
			            		 },
			            		 click:function(e,dt){	     
			            			 var rowid = dt.rowId;
			            			 var row = dt.rowData;
			            			 editService.apply(that, [row]);
			            		 }
			            	 },{
			            		 id : "delete",
			            		 icon:"ui-icon tempo-ui-icon tempo-ui-icon-delete",
			            		 title: TempoUtils.locale("mine.publish-btn-delete"),
			            		 beforeAdd : function(rowId,rowData, btn){
			            			 return !rowData.auth;
			            		 },
			            		 click:function(e,dt){	     
			            			 var rowid = dt.rowId;
			            			 var row = dt.rowData;
			            			 deleteService(row);
			            		 }
			            	 },{
			            		 id : "link",
			            		 icon:"ui-icon tempo-ui-icon tempo-ui-icon-link",
			            		 title: TempoUtils.locale("mine.publish-btn-link"),
			            		 beforeAdd : function(rowId,rowData, btn){
			            			 return false;
			            		 },
			            		 click:function(e,dt){
			            			 var row = dt.rowData;
			            			 var targetId = row.id;
			            			 var target = e.target;
			            			 var clipboard =  $(target).data('clipboard');
			            			 if(!clipboard){
			            				 var tempoBaseUrl = location.protocol + "//" + location.host + contextPath + "/webapi/ai/model/async/execute/" + targetId ;
			            				 $(target).attr('id', "copy_" + targetId);
			            				 $(target).attr('data-clipboard-text', tempoBaseUrl);
			            				 var clipboard = new Clipboard('#copy_' + targetId);
			            				 $(target).data('clipboard', clipboard);
			            				 clipboard.on('success', function(e) {
			            					 $("<div/>").alert({msg : TempoUtils.locale("mine.fuzhichenggong"), height : 180});
			            					 e.clearSelection();
			            					 return;
			            				 });
			            			 }
			            		 }
			            	 },{
			            		 id : "asyncConfig",
			            		 icon:"ui-icon tempo-ui-icon tempo-ui-icon-setting",
			            		 title: TempoUtils.locale("mine.setting"),
			            		 beforeAdd : function(rowId,rowData, btn){
			            			 //return isSyncFlow(rowData);
			            			 return isAsyncFlow(rowData);
			            		 },
			            		 click:function(e,dt){//异步服务环境资源配置弹框
			            			 that.currentData = dt.rowData;
			            			 asyncConfigResource(dt.rowData);
			            		 }
			            	 },{
			            		 id : "test",
			            		 icon:"ui-icon tempo-ui-icon tempo-ui-icon-test",
			            		 title: TempoUtils.locale("mine.test"),
			            		 beforeAdd : function(rowId,rowData, btn){
			            			 //return isSyncFlow(rowData);
			            			 return isSyncFlow(rowData) || isAsyncFlow(rowData);
			            		 },
			            		 click:function(e,dt){
			            			 that.currentData = dt.rowData;
			            			 if(isSyncFlow(that.currentData)) {
			            				 //同步任务
			            				 testSyncConfigFlow(dt.rowData);
			            			 } else if(isAsyncFlow(that.currentData)){
			            				 // 异步服务
			            				 testAsyncConfigFlow(dt.rowData);
			            			 }
			            		 }
			            	 },{
			            		 id : "resource",
			            		 icon:"ui-icon tempo-ui-icon tempo-ui-icon-download",
			            		 title: TempoUtils.locale("mine.publish-sync-resource-title"),
			            		 beforeAdd : function(rowId,rowData, btn){
			            			 return rowData.type == 'sync';
			            		 },
			            		 click:function(e,dt){
			            			 var row = dt.rowData;
			            			 downloadSyncResource.apply(that, [row]);
			            		 }
			            	 }]
			             }
			             ],
			             loadComplete : function(datas){
			            	 var rows = datas.rows;
			            	 $(this).data('rows', rows);
			            	 if(rows && rows.length > 0){
			            		 for (var n = 0; n < rows.length; n++) {
									var row = rows[n];
									var rowEle = $(this).find('#' + row.id);
									var auth = row.isAuth;
									if(auth){
										
									}
								}
			            	 }
			            	 bindServiceGridEvent.apply(that);
			            	 var frow = rows.filter(function(e){ return (e.type == 'sync' || e.type == 'stream') && (e.launchState == 'STARTING') })
			            	 if(frow.length) {
			            		 GridListener.start(frow);
			            	 }
			             },
			             pagination : true
		});
	}

	/**
	 * 校验表单
	 */
	var validateForm = function(dialog){
		return dialog.find('form').formValidate();
	}

	var nameValid = function(e){
		e.attr("ui-role","validatebox");
		e.validatebox({
			valids:[/^[^~!@#\$%\^&\*\+\[\]\|\}\{\\;':",\.\/<>\?`]+$/],
			required: true,
			maxLength : 50,
			autofill:false,
			tip:TempoUtils.locale("mine.service_name_valid_tip"),
		})
	}

	this.initOrrefresh = function(){
		var that = this;
		$('.publish_tab').height($('#publish-mine-config').height()-98)
		if(!this.grid){
			this.initServiceGrid();
			$('#servicesearcher').searchbar({
				placeholder:TempoUtils.locale("mine.searchpublishname"),
				onSearch : function(text){
					var name = text.trim();
					if(name && name.length > 0){
						that.grid.jqGrid('setGridParam',
								{
							postData : {
								name : name
							}
								}).trigger("reloadGrid");
					}else{
						that.grid.jqGrid('setGridParam',
								{
							postData : {themeId : analyseId, name : null}
								}).trigger("reloadGrid");
					}
				}
			});
			$('#mine-opt-service-newbtn').button({
				useRadius : true,
				label : TempoUtils.locale('mine.publish-btn-new'),
				click : function(){
					that.service = {};
					newService.apply(that);
				}
			});
			$('#mine-service-runtime-download').button({
				useRadius : true,
				label : TempoUtils.locale('mine.publish-runtime-download'),
				click : function(){
					downloadRuntime.apply(that);
				}
			});
		}else{
			that.grid.jqGrid('setGridParam',
					{
				postData : {themeId : analyseId, name : null}
					}).trigger("reloadGrid");
		}
	}
	var isSyncFlow = function(row) {
		if(row.type == 'sync') {
			return true;
		} else {
			return false;
		}
	}
	var isAsyncFlow = function(row) {
		if(row.type == 'async') {
			return true;
		} else {
			return false;
		}
	}
	/**
	 * 启动服务前的配置信息
	 */
	var operateOfSetting = function(e, dt) {
		debugger
		var rowData = dt.rowData;
		if(rowData.approveStatus != '1') {
			 $("<div/>").alert({msg : TempoUtils.locale("mine.publish_approve_first"), height : 180});
			 return ;
		 }
		var that = this;
		var type = rowData.type;
		if(rowData.launchState && rowData.launchState != 'NONE') {
			var msg = TempoUtils.locale("mine.shifotingzhitongbufuwu");
			if (type == "stream") {
				msg = TempoUtils.locale("mine.shifotingzhiliufuwu");
			}
			$("<div/>").confirm({
				title: TempoUtils.locale("mine.prompt"),
				msg: msg,
				ok: function() {
					operateFlow.apply(that, [e, dt, {}]);
				}
			})
		} else {
			var dialog = $('<div/>').appendTo($('body')).dialog({
				width : 500,
				height: 400,
				autoOpen : false,
				title: rowData.name + TempoUtils.locale("mine.qidongpeizhi"),
				modal: true,
				resizable: false,
				close:function(){
					dialog.dialog("destroy").remove();
				},
				open : function() {
					//同步服务启动时显示配置
					dialog.html(getResourceHtml());				
					var resMonitorForm = dialog.find("form[id=resForm]");
					initResMonitorForm(resMonitorForm);
					ajaxLoadingResources(resMonitorForm,null,true);//初始化资源环境监控信息
					dialog.find('input').numberbox({
						required: true,
						min: 1,
						precision: 0
					});
					dialog.find("#content").tabs({ heightStyle: "fill" });
				
					var selectMode = dialog.find('select[name=mode]');
					//selectmode 必须有用
					$.ajax({
						url: contextPath + "/api/ai/mine/getClusterParams",
						type: 'post',
						success: function(rs) {
							var result = rs.data;
							var values = [];
							values.push({
								name: TempoUtils.locale("mine.danjimoshi"),
								value: 'SYNC_ON_LOCAL'
							});
							if(result && result.masterType.startsWith('yarn')) {
								values.push({
									name: TempoUtils.locale("mine.jiqunmoshi"),
									value: 'SYNC_ON_YARN'
								});
							};
							values.reverse();
							for(var i in values) {
								var value = values[i];
								$('<option>').text(value.name).attr('value', value.value).appendTo(selectMode);
							};
							selectMode.selectmenu({
								change: function(event, selected) {
									var val = selected.item.value;
									if("SYNC_ON_LOCAL" == val) {
										dialog.find('label[for="driverCpu"]').text("线程数");
										dialog.find('label[for="manageMemory"]').text("内存（GB）");
									} else {
										dialog.find('label[for="driverCpu"]').text("CPU个数");
										dialog.find('label[for="manageMemory"]').text("内存（GB）");
									}
								}
							});
							if(!parseAndFill(dialog,rowData)){
								dialog.find('input[name=cpu]').val(result.driverCpu || 2);
								dialog.find('input[name=memory]').val(result.manageMemory || 2);
							}
						}
					});
				},
				buttons:[{
					text: TempoUtils.locale("mine.publish-btn-start"),
					click:function(){
						if(dialog.find('form').formValidate()) {
							var cpu = dialog.find('input[name=cpu]').val();
							var mem = dialog.find('input[name=memory]').val();
							var mode = dialog.find('select[name=mode]').val();
							operateFlow.apply(that, [e, dt, {cpu: cpu, mem: mem, mode: mode}]);
							dialog.dialog("destroy").remove();
						}
					}
				}, {
					text: TempoUtils.locale("mine.guanbi"),
					click:function(){
						dialog.dialog("destroy").remove();
					}
				}]
			});
			dialog.dialog('open');
		}
	}
	
	//异步服务弹框
	var asyncConfigResource = function(rowData){
		var dialog = $('<div/>').appendTo($('body')).dialog({
			width : 500,
			height: 400,
			autoOpen : false,
			title: rowData.name + TempoUtils.locale("mine.peizhi"),
			modal: true,
			resizable: false,
			close:function(){
				dialog.dialog("destroy").remove();
			},
			open : function() {
				//异步服务环境资源配置
				dialog.html(getResourceHtml());
				var resMonitorForm = dialog.find("form[id=resForm]");
				initResMonitorForm(resMonitorForm);
				ajaxLoadingResources(resMonitorForm,null,true);//初始化资源环境监控信息
				dialog.find('input').numberbox({
					required: true,
					min: 1,
					precision: 0
				});
				
				dialog.find("#content").tabs({ heightStyle: "fill" });
			
				var selectMode = dialog.find('select[name=mode]');
				selectMode.closest("tr").hide();
				//关于回填值 根据rowdata里的params  如果没有 则默认
				if(!parseAndFill(dialog,rowData)){//根据rowData的参数解析和回填环境资源值	若无 则请求后台		
					$.ajax({
						url: contextPath + "/api/ai/mine/publish/getResourceParams",
						type: 'post',
						data:{flowid:rowData.flowid},
						success: function(result) {
							if(result.masterType == "merit-process"){
								dialog.find('input[name=cpu]').val(result.driverCpu );
								dialog.find('input[name=memory]').val(result.driverMemory );
							}else{
								dialog.find('input[name=limitExtendCpu]').val(result.limitExtendCpu );
								dialog.find('input[name=limitExtendMemory]').val(result.limitExtendMemory );
								dialog.find('input[name=cpu]').val(result.driverCpu);
								dialog.find('input[name=memory]').val(result.driverMemory );
								dialog.find("input").closest("tr").show();
								dialog.find('input[name=executors]').val(result.exeProcessNum );
								dialog.find('input[name=execcpu]').val(result.totalExecutorCores );
								dialog.find('input[name=execmemory]').val(result.executorMemory );
								var selectCache = dialog.find('select[name=cacheconfig]');
								selectCache.closest("tr").show();
								var values = [];
								values.push({name: "NONE",value: 'NONE'},
										{name: 'DISK_ONLY',value: 'DISK_ONLY'},
										{name: 'DISK_ONLY_2',value: 'DISK_ONLY_2'},
										{name: 'MEMORY_ONLY',value: 'MEMORY_ONLY'},
										{name: 'MEMORY_ONLY_2',value: 'MEMORY_ONLY_2'},
										{name: 'MEMORY_ONLY_SER',value: 'MEMORY_ONLY_SER'},
										{name: 'MEMORY_ONLY_SER_2',value: 'MEMORY_ONLY_SER_2'},
										{name: 'MEMORY_AND_DISK',value: 'MEMORY_AND_DISK'},
										{name: 'MEMORY_AND_DISK_2',value: 'MEMORY_AND_DISK_2'},
										{name: 'MEMORY_AND_DISK_SER',value: 'MEMORY_AND_DISK_SER'},
										{name: 'MEMORY_AND_DISK_SER_2',value: 'MEMORY_AND_DISK_SER_2'},
										{name: 'OFF_HEAP',value: 'OFF_HEAP'});
								for(var i in values) {
									var value = values[i];
									$('<option>').text(value.name).attr('value', value.value).appendTo(selectCache);
								};
								selectCache.selectmenu().selectmenu('setValue',result.cacheType);
							}
						}
					});
				}
				isOpenPythonLimit();
			},
			buttons:[{
				text: TempoUtils.locale("mine.publish-dialog-sure"),
				click:function(){
					debugger
					if(dialog.find('form').formValidate()) {
						var rs = saveFlowReourcesParams(dialog,rowData);
						 $.post(contextPath + '/api/ai/mine/publish/updateFlowResource', {id: rowData.id, value: rs},
								 function(data) {
							 $('#mine-opt-service-grid').jqGrid().trigger("reloadGrid");
						});
						dialog.dialog("destroy").remove();
					}
				}
			}, {
				text: TempoUtils.locale("mine.guanbi"),
				click:function(){
					dialog.dialog("destroy").remove();
				}
			}]
		});
		dialog.dialog('open');
	}

	/**
	 * 回填资源限制表格的方法
	 * @returns {{limitExtendMemory: *, limitExtendCpu: *}}
	 */
	var ajaxLoadingPythonLimit = function () {
		var limitExtendCpu = 2;
		var limitExtendMemory = 2;
		$.ajax({
			url:contextPath+"/api/ai/mine/getClusterParams",
			type:'post',
			async:true,
			success:function (response) {
				var result=response.data;
				limitExtendCpu = result.limitExtendCpu;
				limitExtendMemory = result.limitExtendMemory;
			}
		});
		return {
			"limitExtendCpu": limitExtendCpu,
			"limitExtendMemory": limitExtendMemory,
		};
	}

	var operateFlow = function(e, dt, setting) {
		var rowid = dt.rowId;
		var row = dt.rowData;
		var id = row.id, flowid = row.flowid, status = row.launchState;
		var param = {
				id: id,
				flowId: flowid,
				status: status || 'NONE',
				mode: setting.mode || row.mode,
				cpu: setting.cpu || 2,
				mem: setting.mem || 2
			};
		var isAlive = function(fn) {
			 $.post(contextPath + '/api/ai/mine/sync/isalive', {id: id, flowId: flowid},
					 function(data) {
				fn(data);
			 });
		 }
		var process = $("<div/>").tempoprogressbar();
		var counter = status == 'RUNNING' ? 25 : 0;
		// 最终服务应该呈现的状态
		var finalTag = (status == 'RUNNING' || status == 'STARTING') ? false : true;
		$.ajax({
			url: contextPath + '/api/ai/mine/sync/operate',
			method: 'post',
			data: param,
			success: function(d){
				setTimeout(function() {
					var fn = arguments.callee;
					isAlive(function(d) {
						if(d == finalTag) {
							 process.tempoprogressbar("destroy");
							 //重新加载列表
							 $('#mine-opt-service-grid').jqGrid().trigger("reloadGrid");
						} else {
							counter++;
							if(counter < 30) {
								setTimeout(fn, 1000);
							} else {
								process.tempoprogressbar("destroy");
								//重新加载列表
								$('#mine-opt-service-grid').jqGrid().trigger("reloadGrid");
							}
						}
					});
				}, 3000);
			}
		});
		 var states = $("#" + dt.rowId).find("td[aria-describedby='mine-opt-service-grid_launchState']");
		 var op = TempoUtils.locale("mine.publish-btn-start");
		 if(status == 'NONE' || !status) {
			 states.html(TempoUtils.locale("mine.zhengzaiqidong")).attr("title", TempoUtils.locale("mine.zhengzaiqidong"));
		 } else {
			 op = TempoUtils.locale("mine.stop");
			 states.html(TempoUtils.locale("mine.zhengzaitizhi")).attr("title", TempoUtils.locale("mine.zhengzaitizhi"));
		 }
		 
	}
	/**
	 * 同步服务的点击测试的弹框
	 */
	var testSyncConfigFlow = function(rowData){
		var that = this;
		$.post(contextPath + '/api/ai/mine/sync/testConfigDialog', rowData, function(res) {
			var testConfigDialog = $(res);
			that.syncConfigDialog = testConfigDialog.appendTo("body");
			that.syncConfigDialog.dialog({
				width : 650,
				height:630,
				autoOpen : false,
				title: rowData.name + TempoUtils.locale("mine.fuwuceshi"),
				modal:true,
				resizable: false,
				close:function(){
					that.syncConfigDialog.dialog("destroy");
				},
				open : function() {
					initSyncDialog(rowData);
					that.syncConfigDialog.find("p.test-title-1,p.test-title-2").css("cursor"," pointer").click(function(e){
						$(e.target).next().toggle();
					})
				},
				buttons:[{
					text: TempoUtils.locale("mine.guanbi"),
					click:function(){
						that.syncConfigDialog.dialog("close");
					}
				}]
			});
			that.syncConfigDialog.dialog('open');
		})
		
	
	}
	/**
	 * 同步服务测试中内嵌的弹框
	 */
	var testSyncFlow = function(rowData,skInfo){
		//修改弹框内容
		var that = this;
		$.post(contextPath + '/api/ai/mine/sync/testdialog', rowData, function(res) {
			var testDialog = $(res);
			that.syncDialog = testDialog.appendTo('body');
			that.syncDialog.dialog({
				width : 650,
				minHeight: 450,
				maxHeight:590,
				autoOpen : false,
				title: rowData.name + TempoUtils.locale("mine.fuwuceshi"),
				modal:true,
				resizable: false,
				close:function(){
					that.syncDialog.dialog("destroy");
					that.syncDialog.empty();
				},
				open : function() {
					bindSyncTest(rowData,skInfo);
                    that.syncDialog.find('input[name=sync-test-data-callname]').focus();
				},
				buttons:[{
					text: TempoUtils.locale("mine.guanbi"),
					click:function(){
						that.syncDialog.dialog("close");
					}
				}]
			});
			that.syncDialog.dialog('open');
		})
		
	}
	var bindSyncTest = function(rowData,skInfo){
		var that = this.syncDialog;
		var form = that.find("form");
		TempoUtils.parserUi(form, {});
		
		var tokens = that.find('span.token').map(function() {
			var clientCode = $(this).attr('clientCode');
			var skCode = $(this).attr('skCode');
			return {clientCode: clientCode, skCode: skCode,callName:$(this).attr('callName')};
		}).get();
		var ccinput = $('input[name=sync-test-data-clientcode]').hide();
		var skinput = $('input[name=sync-test-data-skcode]');
		var callinput = $('input[name=sync-test-data-callname]');
		var cvalue = ccinput.val();
		var select = $('<select />').insertAfter(ccinput);
		var tkObject = {};
		tokens.forEach(function(e) {
			$('<option />').attr('value', e.clientCode).text(e.clientCode).appendTo(select);
			tkObject[e.clientCode] = [e.skCode,e.callName];
		});
		select.selectmenu({
			width: 250,
			select: function(e, ui) {
				ccinput.val(ui.item.value);
				skinput.val(tkObject[ui.item.value][0]);
				callinput.val(tkObject[ui.item.value][1])
			}
		}).selectmenu('setValue', cvalue).selectmenu('refresh');
		that.find('#mine-flow-btn-test').button({
			useRadius : false,
			label : TempoUtils.locale("mine.test"),
			click : function(){

				if(serviceObject && serviceObject.rows && serviceObject.rows.length) {
					serviceObject.rows.forEach(function(e) {
						if(e.id == rowData.id && e.launchState == 'RUNNING') {
							rowData.launchState = 'RUNNING';
						} else if(e.id == rowData.id && e.launchState == 'STARTING') {
							rowData.launchState = 'STARTING';
						}
					})
				}
				console.log(serviceObject, rowData);
				if(rowData.launchState == 'STARTING') {
					$("<div/>").alert({msg : TempoUtils.locale("mine.service-starting"), height : 180});
					return ;
				} else if(!rowData.launchState || rowData.launchState == 'NONE') {
					if(!rowData.ignore) {
						$("<div/>").confirm({
							title: TempoUtils.locale("mine.prompt"),
							msg: TempoUtils.locale("mine.start-service-yes-no"),
							ok: function() {
								operateOfSetting.apply(that, [null, {rowData: rowData}]);
							}
						})
					} else {
						$("<div/>").alert({msg : TempoUtils.locale("mine.qingkaiqifuwu"), height : 180});
					}
					return ;
				}
				if(!form.formValidate()) {
					$("<div/>").alert({msg : TempoUtils.locale("mine.serviceparamisnotnull"), height : 180});
					return ;
				}
				var record = TempoUtils.getRecord(form);
				record['mine-flow-json-area'] = undefined;
				var data = TempoUtils.clone(record);
				var json = {};
				var clientcode = data['sync-test-data-clientcode'];
				var skcode = data['sync-test-data-skcode'];
				//json['name'] = data['sync-test-data-name'];
				delete data['sync-test-data-clientcode'];
				delete data['sync-test-data-skcode'];
				delete data['sync-test-data-name'];
				delete data['serviceAddress'];

				json['rows'] = [data];
				
				var str = JSON.stringify(json, null, 2);
				that.find('#mine-flow-json-area').val(str);
				var process = $("<div/>").tempoprogressbar();
				
				var address = form.find('input[name=serviceAddress]').val();
				var search = window.location.search;
				// 反序列化传入的参数
				var params = TempoUtils.unSerialize(search);
				
				// 使用tomcat中转访问同步服务
				record.address = address;
				$.post(contextPath + '/api/ai/mine/sync/example/' + rowData.id,
						record, 
						function(d) {
					process.tempoprogressbar("destroy");
					var info = [];
					var board = that.find('.mine-flow-test-result');
					if(d.status == "FINISHED") {
						info.push(TempoUtils.locale("mine.ceshizhuangtaichenggong"));
						info.push(TempoUtils.locale("mine.ceshijieguo"));
						for(var r in d.result) {
							info.push("    " + TempoUtils.locale("mine.tongbushuchu") + d.result[r].name);
							for(var num in d.result[r].rows) {
								var row = d.result[r].rows[num];
								var count = d.result[r].count;
								var columns = d.result[r].columns;
								for(var i in columns) {
									var col = columns[i]
									info.push('      "' + col.name + '"："' + row[col.name] + '"');
								}
								info.push("    " + TempoUtils.locale("mine.testCount") + "：" + count);
							}
						}
						info.push(TempoUtils.locale("mine.ceshicuowudaima") + d.code);
					} else {
						info.push(TempoUtils.locale("mine.ceshizhuangtaishibai"));
						info.push(TempoUtils.locale("mine.ceshicuowudaima") + d.code);
						info.push(TempoUtils.locale("mine.cuowuxinxi"));
						info.push(d.error);
					};
					board.val(info.join('\n'));
				});
			}
		});
	}
	var initSyncDialog = function(rowData){
		var that = this.syncConfigDialog;
		var form = that.find("form");
		TempoUtils.parserUi(form, {});
		form.find('[name=sync-test-data-id]').text(rowData.id);
		form.find('[name=sync-test-data-name]').text(rowData.name);
		form.find('[name=sync-test-data-explain]').text(rowData.name);	
		
		var runConfig = form.find("#immutableflowparams td:nth-child(2n)");
		var obj = JSON.parse(rowData.flowParams).filter(function(v){if(v["$configResources$"]) return true;});
		if(obj.length > 0 ){
			var json = JSON.parse(obj[0]["$configResources$"]);
			if(Object.keys(json).length != 0){
				$(that.find('td[name="cpu"]')).text(json.cpu);
				$(that.find('td[name="memory"]')).text(json.mem);
				$(that.find('td[name="mode"]')).text(json.mode == "SYNC_ON_YARN"?TempoUtils.locale("mine.jiqunmoshi"):TempoUtils.locale("mine.danjimoshi"));
			}
		}
		sdkDownload(that, rowData);
		//初始化测试按钮
		syncTest(that, rowData);
		//加载实例代码 targetId jscode
		var $jscode = form.find("#jscodesync");
		$.post(contextPath + '/api/ai/mine/publish/api/'+rowData.id,rowData, function(res) {
			$("<textarea id='sync-js-code'>"+res+"</textarea>").appendTo($jscode);
		});
	}	
	
	var syncTest = function(that, rowData){
		that.find('#mine-flow-sync-test').button({
			height:24,
			icon:"ui-icon tempo-ui-icon tempo-ui-icon-test",
			click : function(e){
				debugger
				testSyncFlow(rowData);
			}
		});
	}
	/*	var labels = that.find('label.input-column');
		var columns = [];
		for(var i = 0; i < labels.length; i++) {
			columns.push($(labels.get(i)).text());
		}
		console.log(columns);
		var id = rowData.id, flowid = rowData.flowid, status = rowData.launchState;
		

		that.find('#tempo-mine-flow-service-test').submit(function(){
			return false;
		})
	}*/
	
	
	
	var sdkDownload = function(that, rowData) {
		that.find('#mine-flow-sdk-dlownload').button({
			height:24,
			icon:"ui-icon tempo-ui-icon tempo-ui-icon-download",
			click : function(e){
				TempoUtils.download({
					url: contextPath + '/api/ai/mine/sync/sdk',
					data: {
						id: rowData.id
					}
				});
				var btn = $(this).button('disable');
				setTimeout(function() {
					btn.button('enable');
				}, 5000);
				return false;
			}
		});
		/**
		 * 下载示例代码
		 */
		var codeUrl = contextPath + '/api/ai/mine/sync/clientcode';
		if(rowData.type != 'sync') {
			codeUrl = contextPath + '/api/ai/mine/async/clientcode';
		}
		that.find('#mine-flow-code-download').button({
			height:24,
			icon:"ui-icon tempo-ui-icon tempo-ui-icon-download",
			click : function(e){
				TempoUtils.download({
					url: codeUrl,
					data: {
						id: rowData.id,
						flowid: rowData.flowid
					}
				});
				var btn = $(this).button('disable');
				setTimeout(function() {
					btn.button('enable');
				}, 5000);
				return false;
			}
		});
		
		
	}
	
	var jsonCopy = function(that, rowData) {
		that.find('#mine-flow-btn-copyjson').button({
			height: 24,
			icon:"ui-icon tempo-ui-icon tempo-ui-icon-sequence",
			click : function(e){
				var text = that.find("#mine-flow-json-area").val();
				copyText(text, e);
				return false;
			}
		});
	}
	/////////////////////////////////////////////////////////////////
	//
	//
	//                     异步服务测试界面
	//
	//
	/////////////////////////////////////////////////////////////////
	var testAsyncConfigFlow = function(rowData){
		var that = this;
		if(!rowData.auth) {
			$("<div/>").alert({msg : TempoUtils.locale("mine.qingshouquanfuwu"), height : 180});
			return ;
		}
		//新增一个弹窗，在弹窗内部在弹出原来的经过修改后的弹窗
		$.post(contextPath + '/api/ai/mine/async/testconfig', rowData, function(res) {
			var testDialog = $(res);
			that.asyncTestDialog = testDialog.appendTo('body');
			that.asyncTestDialog.dialog({
				width : 650,
				height: 630,
				autoOpen : false,
				title: rowData.name + TempoUtils.locale("mine.fuwuceshiyibu"),
				modal:true,
				resizable: false,
				close:function(){
					that.asyncTestDialog.dialog("destroy");
					that.asyncTestDialog = null;
					if(!rowData.ignore) {
						$('#mine-opt-service-grid').jqGrid().trigger('reloadGrid');
					}
				},
				open : function() {
					initAsyncDialog(rowData);
					that.asyncTestDialog.find("p.test-title-1,p.test-title-2").css("cursor"," pointer").click(function(e){
						$(e.target).next().toggle();
					})
				},
				buttons:[{
					text: TempoUtils.locale("mine.guanbi"),
					click:function(){
						that.asyncTestDialog.dialog("close");
					}
				}]
			});
			that.asyncTestDialog.dialog('open');
		})	
	}
	var testAsyncFlow = function(rowData) {
		var that = this;
		$.post(contextPath + '/api/ai/mine/async/testdialog', rowData, function(res) {
			var testDialog = $(res);
			that.asyncDialog = testDialog.appendTo('body');
			that.asyncDialog.dialog({
				width : 650,
				height: 550,
				autoOpen : false,
				title: rowData.name + TempoUtils.locale("mine.fuwuceshiyibu"),
				modal:true,
				resizable: false,
				close:function(){
					that.asyncDialog.dialog("destroy");
					that.asyncDialog = null;
					if(!rowData.ignore) {
						$('#mine-opt-service-grid').jqGrid().trigger('reloadGrid');
					}
				},
				open : function() {
					var form = $(this).find("form");
					TempoUtils.parserUi(form, {});
					//将其他的授权码添加进来，组成下拉框供选择
					var tokens = $(this).find('span.token').map(function() {
						var clientCode = $(this).attr('clientCode');
						var skCode = $(this).attr('skCode');
						return {clientCode: clientCode, skCode: skCode,callName:$(this).attr('callName')};
					}).get();
					var skinput = form.find('input[name=async-test-data-skcode]');
					var callinput = form.find('input[name=async-test-data-callname]');
					var select = form.find('#selectCode');
					var tkObject = {};
					debugger
					tokens.forEach(function(e) {
						$('<option />').attr('value', e.clientCode).text(e.clientCode).appendTo(select);
						tkObject[e.clientCode] = [e.skCode,e.callName];
					});
					select.selectmenu({
						width: 250,
						select: function(e, ui) {
							skinput.val(tkObject[ui.item.value][0]);
							callinput.val(tkObject[ui.item.value][1]);
							//原代码中往后台传参的组件
							form.find('[name=async-test-data-clientcode]').val(ui.item.value);
						}
					}).selectmenu('setValue', select.prev().val()).selectmenu('refresh');
					form.find('[name=serviceId]').val(rowData.id);
					var tempoBaseUrl = location.protocol + "//" + location.host + contextPath + "/webapi/ai/model/async/execute/" + rowData.id ;
					form.find('[name=async-test-data-url]').val(tempoBaseUrl);
					bindAsyncEvent(rowData);
					that.asyncDialog.find('textarea').focus();
				},
				buttons:[{
					text: TempoUtils.locale("mine.guanbi"),
					click:function(){
						that.asyncDialog.dialog("close");
					}
				}]
			});
			that.asyncDialog.dialog('open');
		})
	}
	
	var getServiceInfo = function(){
		debugger
		var that = this.asyncDialog;
		var url = that.find('input[name="async-test-data-url"]').val();
		var clientCode = that.find('input[name="async-test-data-clientcode"]').val();
		var skCode = that.find('input[name="async-test-data-skcode"]').val();
		
		if(!url || url.trim().length == 0){
			return null;
		}
		if(!clientCode || clientCode.trim().length == 0){
			return null;
		}
		if(!skCode || skCode.trim().length == 0){
			return null;
		}
		url = url.substr(url.lastIndexOf('/')+1)
		return {
			url : url,
			clientCode:clientCode,
			skCode:skCode
		}
		return;
	}
	
	var initAsyncDialog = function(rowData){
		var that = this.asyncTestDialog;
		var form = that.find("form");
		TempoUtils.parserUi(form, {});
		var targetId = rowData.id;
		var tempoBaseUrl = location.protocol + "//" + location.host + contextPath + "/webapi/ai/model/async/execute/" + targetId ;
		form.find('[name=async-test-data-url]').text(tempoBaseUrl);
		form.find('[name=async-test-data-id]').text(targetId);
		form.find('[name=async-test-data-name]').text(rowData.name);
		form.find('[name=async-test-data-explain]').text(rowData.name);	
		sdkDownload(that, rowData);//初始化下载按钮
		//初始化测试按钮
		asyncTest(that, rowData);
		//加载实例代码 targetId jscode
		var $jscode = form.find("#jscode");
		$.post(contextPath + '/api/ai/mine/publish/api/'+targetId,rowData, function(res) {
			var result = res;
			$("<textarea id='async-js-code'>"+result+"</textarea>").appendTo($jscode);
		});
		//加载不可变的流程参数
		var imuutableFlowParams = JSON.parse(rowData.flowParams);
		if(!(dataSourceCache && dataSourceCache['datasource'])){
			$.ajax({
				url:contextPath + '/api/ai/node/io/list-datasources',
				type:'post',
				async:false,
				success:function(rs) {
					var data = rs.data;
					dataSourceCache['datasource'] = data;
				}
			})
		}
		imuutableFlowParams.forEach(function(v,i){
			if(v.paramType && v.paramType == "datasource"){
				var pavalArray = dataSourceCache['datasource'].filter(function(w){if(w.code == v.paramValue)return w});
				var paval = '';
				if(pavalArray.length > 0){
					paval = pavalArray[0].name;
				}
				form.find("#immutableflowparams").append("<tr>" + 
						"					<td >"+v.paramName+"</td>" + 
						"					<td >"+paval+"</td>" + 
						"				</tr>");
				
			}else if(v.paramName){
				form.find("#immutableflowparams").append("<tr>" + 
						"					<td >"+v.paramName+"</td>" + 
						"					<td >"+v.paramValue+"</td>" + 
						"				</tr>");
			}
		})
	}
	
	var asyncTest = function(that, rowData){
		that.find('#mine-flow-async-test').button({
			height:24,
			icon:"ui-icon tempo-ui-icon tempo-ui-icon-test",
			click : function(e){
				debugger
				testAsyncFlow(rowData);
			}
		});
	}
	
	var stack = ['SUBMITING', 'SUBMITTED', 'STARTING', 'RUNNING'];
	var bindAsyncEvent = function(rowData){
		var that = this.asyncDialog;
		var board = that.find('#mine-flow-json-area');
		var showJson = function(text, append) {
			if(append) {
				var value = board.val();
				board.val(value + "\n" + text);
			} else {
				board.val(text);
			}
		}
		var _eid = read(rowData.id);
		if(_eid) {
			that.find('input[name="eid"]').val(_eid);
			updateAsyncState(rowData);
		}
		that.find('.exebtn').click(function(){
			debugger
			var serviceinfo = getServiceInfo();
			var eid = that.find('input[name="eid"]').val();
			if(eid) {
				$("<div/>").alert({
					msg : TempoUtils.locale("mine.renwuyijingzhixing"),
					width : '500px'
				});
				return ;
			}
			if(serviceinfo){
				var ptable = that.find('#ptable tbody tr');
				var params = { };
				if(ptable && ptable.size() > 0){
					ptable.each(function(i){
						 var pname = $(this).find('input[name="pname"]').val();
						 var pvalue = $(this).find('input[name="pvalue"]').val();
						 if(pname && pname.trim().length > 0 && pvalue && pvalue.trim().length > 0){
							 params[pname]= pvalue;
						 }
					});
				}
				var record = TempoUtils.clone(params);
				delete record.requestId
				// record.clientCode = serviceinfo.clientCode;
				// record.skCode = serviceinfo.skCode;
				var str = JSON.stringify(record, '', 2);
				showJson(TempoUtils.locale("mine.qingqiushujugeshi")+"\n" + str);
				var process = $("<div/>").tempoprogressbar();
				requestToken(serviceinfo.skCode , function(result) {
					if(!result.success) {
						process.tempoprogressbar("destroy");
					}
				},function(token) {
					$.ajax({
						url : contextPath + "/webapi/ai/model/async/execute/" + serviceinfo.url,
						data : params,
						headers: {
							"App-Key": serviceinfo.clientCode,
							"App-Token": token
						},
						success : function(response){
							var result = response.data;
							var str = JSON.stringify(result, '', 2);
							showJson(TempoUtils.locale("mine.fanhuishujugeshi")+"\n" + str, true);
							process.tempoprogressbar("destroy");
							that.find('#statusResult').text('');
							that.find('#killResult').text('');
							if(result && result.eid) {
								that.find('input[name="eid"]').val(result.eid);
								updateAsyncState(rowData);
								store(rowData.id, result.eid);
							} else {
								$("<div/>").alert({
									msg : response.message,
									width : '500px'
								});
							}
						}
					})
				});
			}else{
				$("<div/>").alert({
					msg : TempoUtils.locale("mine.fuwudizhikehuduanbiaomheshouquanma"),
					width : '500px'
				});
			}
			return false;
		});
		
		that.find('#statusbtn').click(function(){
			debugger
			var serviceinfo = getServiceInfo();
			if(serviceinfo){
				var eid = that.find('input[name="eid"]').val();
				if(!eid || eid.trim().length == 0){
					$("<div/>").alert({
						msg : TempoUtils.locale("mine.zhixingidweikong"),
						width : '250px'
					});
				}else{
					var data = {
						eid : eid
					};
					var record = TempoUtils.clone(data);
					delete record.requestId;
					record.clientCode = serviceinfo.clientCode;
					record.skCode = serviceinfo.skCode;
					var str = JSON.stringify(record, '', 2);
					showJson(TempoUtils.locale("mine.qingqiushujugeshi")+"\n" + str);
					var process = $("<div/>").tempoprogressbar();
					requestToken(serviceinfo.skCode , function(result) {
						if(!result.success) {
							process.tempoprogressbar("destroy");
						}
					},function(token) {
						$.ajax({
							url : contextPath + "/webapi/ai/model/async/status/" + serviceinfo.url,
							data : data,
							headers: {
								"App-Key": serviceinfo.clientCode,
								"App-Token": token
							},
							success : function(response){
								var result = response.data;
								var str = JSON.stringify(result, '', 2);
								showJson(TempoUtils.locale("mine.fanhuishujugeshi")+"\n" + str, true);
								process.tempoprogressbar("destroy");
								if(result) {
									that.find('#statusResult').text(response.message);
								}

								if(result.error == '0' && stack.indexOf(result.status) == -1) {
									clearState(rowData.id);
								}
								if('FINISHED' == result.status) {
									$("<div/>").alert({
										msg : TempoUtils.locale("mine.ceshichenggong"),
										width : '500px'
									});
								} else if('FAILED' == result.status) {
									$("<div/>").alert({
										msg : TempoUtils.locale("mine.ceshishibai"),
										width : '500px'
									});
								}
								$('#mine-opt-service-grid').jqGrid().trigger('reloadGrid');
							}
						})
					});
				}
			}else{
				$("<div/>").alert({
					msg : TempoUtils.locale("mine.fuwudizhikehuduanbiaomheshouquanma"),
					width : '500px'
				});
			}
			return false;
		});
		
		that.find('#killbtn').click(function(){
			var serviceinfo = getServiceInfo();
			if(serviceinfo){
				var eid = that.find('input[name="eid"]').val();
				if(!eid || eid.trim().length == 0){
					$("<div/>").alert({
						msg : TempoUtils.locale("mine.zhixingidweikong"),
						width : '250px'
					});
				}else{
					// var requestId = window.btoa(serviceinfo.clientCode + "#" + serviceinfo.skCode + "#" + new Date().getTime())
					var data = {
						eid : eid
					};
					var str = JSON.stringify(data, '', 2);
					showJson(TempoUtils.locale("mine.qingqiushujugeshi")+"\n" + str);
					var process = $("<div/>").tempoprogressbar();
					requestToken(serviceinfo.skCode , function(result) {
						if(!result.success) {
							process.tempoprogressbar("destroy");
						}
					},function(token) {
						$.ajax({
							url : contextPath + "/webapi/ai/model/async/kill/" + serviceinfo.url,
							data : {
								eid : eid
							},
                            headers: {
                                "App-Key": serviceinfo.clientCode,
                                "App-Token": token
                            },
							success : function(response){
								var result = response.data || {};
								var str = JSON.stringify(result, '', 2);
								showJson(TempoUtils.locale("mine.fanhuishujugeshi")+"\n" + str, true);
								process.tempoprogressbar("destroy");
								if(result) {
									that.find('#killResult').text(response.message);
								}
								if(response.success) {
									clearState(rowData.id);
								}
								$('#mine-opt-service-grid').jqGrid().trigger('reloadGrid');
							},
							error : function(){
								process.tempoprogressbar("destroy");
								$("<div/>").alert({
									msg : "系统错误，请联系管理员！"
								});
							}
						})
					});
				}
			}else{
				$("<div/>").alert({
					msg : TempoUtils.locale("mine.fuwudizhikehuduanbiaomheshouquanma"),
					width : '500px'
				});
			}
			return false;
		});
		
		that.find('.job-param-addbtn').click(function(){
			var ptable = that.find('#ptable tbody');
			var tr = $('<tr>').appendTo(ptable);
			var pnameLabelTd = $('<td>').appendTo(tr);
			var pnameLabel = $('<label>').appendTo(pnameLabelTd).addClass('formLayoutTit').text(TempoUtils.locale("mine.canshumingcheng"));
			var pnameInputTd = $('<td>').appendTo(tr);
			var pnameInput = $('<input>').appendTo(pnameInputTd).attr('name','pname').validatebox();
			
			var pvalueLabelTd = $('<td>').appendTo(tr);
			var pvalueLabel = $('<label>').appendTo(pvalueLabelTd).addClass('formLayoutTit').text(TempoUtils.locale("mine.canshuzhi"));
			var pvalueInputTd = $('<td>').appendTo(tr);
			$('<input>').appendTo(pvalueInputTd).attr('name','pvalue').validatebox({width : 220});
			$('<span>').addClass('param-delete-btn ui-icon ui-icon-minus')
				.appendTo(pvalueInputTd)
				.on('click', function(e) {
					$(this).parents('tr').remove();
				})
				.on('selectstart', function() {
					return false;
				});
			
		});
		
	}
	/**
	 * 存储执行id
	 */
	var store = function(id, eid) {
		if(window.localStorage) {
			window.localStorage["mine_async_" + id] = eid;
		}
	}
	/**
	 * 读取执行id
	 */
	var read = function(id) {
		if(window.localStorage) {
			return window.localStorage["mine_async_" + id];
		}
		return undefined;
	}
	/**
	 * 清除状态
	 */
	var clearState = function(id) {
		var that = this.asyncDialog;
		that.find('input[name="eid"]').val('');
		if(window.localStorage) {
			if(window.localStorage["mine_async_" + id]) {
				delete window.localStorage["mine_async_" + id];
			}
		}
		setTimeout(function() {
			$('#mine-opt-service-grid').jqGrid().trigger('reloadGrid');
		}, 2000);
	}
	var updateAsyncState = function(rowData) {
		var that = this.asyncDialog;
		if(!that) return ;
		var serviceinfo = getServiceInfo();
		
		if(serviceinfo){
			var eid = that.find('input[name="eid"]').val();
			if(!eid || eid.trim().length == 0){
				console.error("eid is null");
				return ;
			}else{
				requestToken(serviceinfo.skCode , $.noop,function(token) {
					$.ajax({
						url : contextPath + "/webapi/ai/model/async/status/" + serviceinfo.url,
						data : {
							eid : eid
						},
						headers: {
							"App-Key": serviceinfo.clientCode,
							"App-Token": token
						},
						success : function(res){
							var result = res.data;
							if(result) {
								that.find('#statusResult').text(res.message);
								if(result.status && stack.indexOf(result.status) > -1) {
									setTimeout(function(){
										updateAsyncState(rowData);
									}, 2000);
								} else {
									clearState(rowData.id);
								}
							}
						}
					})
				});
			}
		}
	}
	
	var copyText = function(text, e) {
		 var targetId = ("" + Math.random()).replace(/\./g, "");
		 var target = e.target;
		 var tempoBaseUrl = text;
		 $(target).attr('id', "copy_" + targetId);
		 $(target).attr('data-clipboard-text', tempoBaseUrl);
		 var clipboard = new Clipboard('#copy_' + targetId);
		 $(target).data('clipboard', clipboard);
		 clipboard.on('success', function(e) {
			 $("<div/>").alert({msg : TempoUtils.locale("mine.fuzhichenggong"), height : 180});
			 e.clearSelection();
			 return false;
		 });
	}
	
	var fillServerInput = function(urlInput, clientCodeInput, skCodeInput) {
		urlInput.val("");
		clientCodeInput.val("");
		skCodeInput.val("");
	}
	
	/**
	 * 下载同步服务的资源包
	 */
	var downloadSyncResource = function(row) {
		TempoUtils.download({
			url: contextPath + "/api/ai/mine/sync/downloadSyncResource/" + row.id,
			data : {}
		});
	}
	//绑定新加的环境资源监控面板的事件
	var initResMonitorForm = function(resMonitorForm,API){
		//设置resMonitorForm的样式
		resMonitorForm.find("div").css("margin-bottom","30px").find('span:gt(0)').css("padding-right","10px").css("padding-left","10px").css("border-left","1px solid black");
		resMonitorForm.find("div").find('span:eq(0)').css("padding-right","10px");
		resMonitorForm.find("table tr td:nth-child(1)").css("width","100px");
		resMonitorForm.find("fieldset").css("margin-top","0px");
		
		resMonitorForm.find("table td").css("border","1px solid #dddddd").css("text-align","center ");
		resMonitorForm.find("table tr:nth-child(1) td").css("color","#5b6e85").css("font-weight","bold")
					  .css("border-top","1px solid #dae0e9").css("border-bottom","2px solid #dae0e9").css("line-height","23px");
		resMonitorForm.find("table tr td:nth-child(1)").css("width","55px");
		resMonitorForm.find("table tr:nth-child(3)").css("background","#f8fafd");
		//资源环境参数的点击事件
		resMonitorForm.find(".resEventSpan").off('click').on('click',function(evt){
			
				var that = this;
				resMonitorForm.find("table[id!="+that.id+"Table]").hide();
				resMonitorForm.find("div").find("span[id!="+that.id+"]").css("color","black");
				resMonitorForm.find("#"+that.id).css("color","#2098e6");
				resMonitorForm.find("table[id="+that.id+"Table]").show();
				if(that.id == 'resMonitorCurrentUser'){
					resMonitorForm.find("table[id='resMonitorCurrentUserTable']").prev('span').css("display","block");
				}else{
					resMonitorForm.find("table[id='resMonitorCurrentUserTable']").prev('span').hide();
				}
				//每次点击都重新加载资源情况resMonitorCurrentUserTable
//				$this._ajaxLoadingResources(resMonitorForm,that.id+"Table");
		});
		resMonitorForm.find("a").off('click').on('click',function(e){
			if(API){
				var mask = $("<div/>").partprogressbar({targetDiv:resMonitorForm});
			}else{
				var mask = $("<div/>").tempoprogressbar();
			}
			ajaxLoadingResources(resMonitorForm,mask,null,API);
		});
	}


	/**
	 * tag 标志是否添加遮罩，点击刷新图标触发tagtrue遮罩，点击页签不触发
	 * @param resMonitorForm
	 * @param mask
	 * @param tag
	 * @param API
	 */
	var ajaxLoadingResources = function(resMonitorForm,mask,tag,API){
		if(tag == true) {
			mask = $("<div/>").tempoprogressbar();
		}
		var initResMonitorLoacalTable = function(datas){
			var $table = resMonitorForm.find("#resMonitorLocalTable");
			var keys = Object.keys(datas);
			for(var i = 0 ; i < keys.length ; i++){
				var row1Array = $table.find("tr:eq("+(i*2+1)+") label");
				var row2Array = $table.find("tr:eq("+(i*2+2)+") label");
				if(row1Array.length == 0 &&  row2Array.length ==0){
					resMonitorForm.find("#resMonitorLocalTable tbody").append("<tr>"+$table.find("tr:eq(1)").html()+"</tr>");
					resMonitorForm.find("#resMonitorLocalTable tbody").append("<tr style='background: rgb(248, 250, 253);'>"+$table.find("tr:eq(2)").html()+"</tr>");
					row1Array = $table.find("tr:eq("+(i*2+1)+") label");
					row2Array = $table.find("tr:eq("+(i*2+2)+") label");
				}
				var data = datas[keys[i]];
				var allMemory = data[3].toFixed(2);
				var leftMemory = data[4].toFixed(2);
				var usedMemory = (allMemory - leftMemory).toFixed(2);
				$(row1Array[0]).text(keys[i]);
				$(row1Array[1]).text(data[0]);
				$(row1Array[2]).text(data[1].toFixed(2)+"%");
				$(row1Array[3]).text(data[2].toFixed(2)+"%");
				$(row2Array[0]).text(allMemory);//总内存
				$(row2Array[1]).text(usedMemory);//已使用内存
				$(row2Array[2]).text(leftMemory);//可用内存=已缓存+空闲
			}

		}
		var initResMonitorClusterTable = function(data){
			var $table = resMonitorForm.find("#resMonitorClusterTable");
			var row1Array = $table.find("tr:eq(1) label");
			var row2Array = $table.find("tr:eq(2) label");
			var allocateGB = (data['allocatedMB']/1024).toFixed(2);
			var availableGB = (data['availableMB']/1024).toFixed(2);
			var allGB = ( Number(allocateGB)+Number(availableGB) ).toFixed(2);
			$(row1Array[0]).text(Number(data['allocatedVirtualCores'])+Number(data['availableVirtualCores']));
			$(row1Array[1]).text(data['allocatedVirtualCores']);
			$(row1Array[2]).text(data['availableVirtualCores']);
			$(row2Array[0]).text(allGB);//总内存
			$(row2Array[1]).text(allocateGB);//已使用内存
			$(row2Array[2]).text(availableGB);//可用内存=已缓存+空闲
		}

		/**
		 * k8s模式下集群资源监控情况
		 * @param data
		 */
		var initK8sClusterTable = function(data){
			var $table = resMonitorForm.find("#resMonitorClusterTable");
			var row1Array = $table.find("tr:eq(1) label");
			var row2Array = $table.find("tr:eq(2) label");
			var allocateGB = (data['executeMemory']).toFixed(2);
			var allGB = (data['k8sTotalMemory']).toFixed(2);
			var availableGB = (Number(allGB)-Number(allocateGB)).toFixed(2);
			$(row1Array[0]).text(data['k8sTotalCpu']);
			$(row1Array[1]).text(data['driverCpu']);
			$(row1Array[2]).text(Number(data['k8sTotalCpu'])-Number(data['driverCpu']));
			$(row2Array[0]).text(allGB);//总内存
			$(row2Array[1]).text(allocateGB);//已使用内存
			$(row2Array[2]).text(availableGB);//可用内存=已缓存+空闲
		}

		var initResCurrentResourceTable = function(data){
			var $table = resMonitorForm.find("#resCurrentResourceTable");
			var row1Array = $table.find("tr:eq(1) label");
			var row2Array = $table.find("tr:eq(2) label");
			var allGB = data["allMemory"]?Number(data["allMemory"]).toFixed(2):"";
			var availableGB = allGB != ""?(Number(data["allMemory"])-Number(data['useMemory'])).toFixed(2):"";
			var allCpu = data["allCpu"]?Number(data["allCpu"]):"";
			var availableCpu = allGB != ""?Number(data["allCpu"])-Number(data['useCpu']):"";
			$(row1Array[0]).text(allCpu);
			$(row1Array[1]).text(data['useCpu']);
			$(row1Array[2]).text(availableCpu);
			$(row2Array[0]).text(allGB);//总内存
			$(row2Array[1]).text(data['useMemory'].toFixed(2));//已使用内存
			$(row2Array[2]).text(availableGB);//可用内存=已缓存+空闲
		}
		var initResMonitorCurrentUserTable = function(data,yarn0){
			var $table = resMonitorForm.find("#resMonitorCurrentUserTable");
			var row1Array = $table.find("tr:eq(1) label");
			var row2Array = $table.find("tr:eq(2) label");
			var maxMermoryGB = (data['maxMermory']/1024).toFixed(2);
			var usedMermoryGB = (data['usedMemory']/1024).toFixed(2);
			var leftMermoryGB = (maxMermoryGB - usedMermoryGB).toFixed(2);
			var leftCores = data['maxCores'] - data['usedCores'];
			//队列不存在，资源显示可能有问题，需要特殊处理，修改56118bug
			if (yarn0 != null) {
				if (parseFloat(leftCores) > parseFloat(yarn0["availableVirtualCores"])) {
					leftCores = yarn0["availableVirtualCores"];
					data['usedCores'] = data['maxCores'] - leftCores;
				}
				if (parseFloat(leftMermoryGB) > parseFloat((yarn0['availableMB'] / 1024).toFixed(2))) {
					leftMermoryGB = (yarn0['availableMB'] / 1024).toFixed(2);
					usedMermoryGB = (maxMermoryGB - leftMermoryGB).toFixed(2);
				}
			}
			
			$(row1Array[0]).text(data['maxCores']);
			$(row1Array[1]).text(data['usedCores']);
			$(row1Array[2]).text(leftCores);
			$(row2Array[0]).text(maxMermoryGB);//总内存
			$(row2Array[1]).text(usedMermoryGB);//已使用内存
			$(row2Array[2]).text(leftMermoryGB);//可用内存=已缓存+空闲
			//赋值当前队列名称
			resMonitorForm.find("#curentUserQueueName").text(TempoUtils.locale("mine.flow_res_curUserName")+data.fullQueueName);
			resMonitorForm.find("li[aria-controls=res-curUser]").attr("title", TempoUtils.locale("mine.flow_res_curUserName") + data.fullQueueName)
		}
		
		$.ajax({
			url:contextPath+"/api/ai/mine/getResMonitor",
			type:'post',
			success:function(rs){
				if(mask != null){
					if(API){
						mask.partprogressbar('close');
					}else{
						mask.tempoprogressbar('close');
					}
				}
				if(rs.Local != null){
					initResMonitorLoacalTable(rs.Local);
				}
				if(rs.Yarn != null && rs.k8s == undefined){
					if (rs.Yarn[0] != null) {
						initResMonitorClusterTable(rs.Yarn[0]);
					} else {
						resMonitorForm.find("#resMonitorClusterTable").parent().remove();
						resMonitorForm.find("a[href='#res-cluster']").parent().remove();
					}
					if (rs.Yarn[1] != null) {
						initResMonitorCurrentUserTable(rs.Yarn[1], rs.Yarn[0]);
					} else {
						resMonitorForm.find("#resMonitorCurrentUserTable").parent().remove();
						resMonitorForm.find("a[href='#res-curUser']").parent().remove();
					}
				}else if(rs.Yarn != null && rs.k8s != undefined && rs.k8s != null){
					initK8sClusterTable(rs.k8s);
					resMonitorForm.find("#resMonitorCurrentUserTable").parent().remove();
					resMonitorForm.find("a[href='#res-curUser']").parent().remove();
				}else{
					resMonitorForm.find("#resMonitorClusterTable").parent().remove();
					resMonitorForm.find("a[href='#res-cluster']").parent().remove();

					resMonitorForm.find("#resMonitorCurrentUserTable").parent().remove();
					resMonitorForm.find("a[href='#res-curUser']").parent().remove();
				}
				if (rs.resource != null) {
					initResCurrentResourceTable(rs.resource);
				} else {
					resMonitorForm.find("#resCurrentResourceTable").parent().remove();
					resMonitorForm.find("a[href='#res-monitor']").parent().remove();
				}
			},
			complete:function(){
				if(mask != null){
					if(API){
						mask.partprogressbar('close');
					}else{
						mask.tempoprogressbar('close');
					}
				}
			}
		});
	
	}

	/**
	 *关闭h资源限制时不显示资源限制列表的方法
	 */
	var isOpenPythonLimit = function(){
		debugger
		$.ajax({
			url: contextPath + "/api/ai/mine/getClusterParams",
			type: 'post',
			success: function (response) {
				debugger
				var result = response.data;
				var isOpen = result.resourceLimitEnable;
				if(!isOpen){
					$("a[href='#resourceParamConfigTab']").hide();
					$("#resourceParamConfigTab").hide();
				}
			}
		});
	}

	var getResourceHtml = function(type){
		var html ="<div id='content'> <ul id='ul'>" ;
		var cpuLabel = TempoUtils.locale("mine.cpugeshu");
		var memLabel = TempoUtils.locale("mine.neicundaxiao");
		var setpythonCpu=TempoUtils.locale("mine.flow-rumtime-param-pythonCpu");
		var setpythonMemory=TempoUtils.locale("mine.flow-rumtime-parm-pythonMemory-label");
		if("sync" == type){
			html+="<li ><a href=\"#serviceInstance\"><span>"+TempoUtils.locale("mine.sync_flow_instance")+"</span></a></li>";
		}
		html += " <li><a href=\"#serviceParamConfig\"><span>"+TempoUtils.locale("mine.flow_env_config")+"</span></a></li>";
		html +=	"<li><a href=\"#serviceParamMonitor\"><span>"+TempoUtils.locale("mine.flow_res_config")+"</span></a></li>";
		if (type == 'async') {
			html +=	"<li><a href=\"#resourceParamConfigTab\"><span>"+TempoUtils.locale("mine.flow_resourceset_config")+"</span></a></li>";
		}
		html +=	"</ul>";
		if("sync" == type){
			html += '<div id="serviceInstance" style="overflow: auto"><table id="mine-opt-instance-grid" ></table></div>';
		}
		html += '<div id="serviceParamConfig"><form><table>';
		html += '<tr><td style="width:120px;text-align: right;padding-right: 5px;"><label for="driverCpu">'+cpuLabel+'</label></td><td><input name="cpu" value="1"></td></tr>';
		html += '<tr><td style="width:120px;text-align: right;padding-right: 5px;"><label for="manageMemory">'+memLabel+'</label></td><td><input name="memory" value="1"></td></tr>';
		html += '<tr style="display:none"><td style="width:120px;text-align: right;padding-right: 5px;"><label>'+TempoUtils.locale("mine.zxqgs")+'</label></td><td><input name="executors" value="1"></td></tr>';
		html += '<tr style="display:none"><td style="width:120px;text-align: right;padding-right: 5px;"><label>'+TempoUtils.locale("mine.yxcpugs")+'</label></td><td><input name="execcpu" value="1"></td></tr>';
		html += '<tr style="display:none"><td style="width:120px;text-align: right;padding-right: 5px;"><label>'+TempoUtils.locale("mine.yxnc")+'(GB)</label></td><td><input name="execmemory" value="1"></td></tr>';
		html += '<tr style="display:none"><td style="width:120px;text-align: right;padding-right: 5px;"><label>'+TempoUtils.locale("mine.hcsz")+'</label></td><td><select name="cacheconfig" ></select></td></tr>';
		html += '<tr ><td style="width:120px;text-align: right;padding-right: 5px;"><label>管理GPU个数</label></td><td><input name="gpu" value="0"></td></tr>';
		html += '<tr><td style="width:120px;text-align: right;padding-right: 5px;"><label>'+TempoUtils.locale("mine.qidongmoshi")+'</label></td><td><select name="mode"></select></td></tr>';
		html += '</table></form></div>';

		if (type == 'async') {
			html += '<div id="resourceParamConfigTab"><form><table id="resourcesLimit">';
		    html += '<tr><td style="width:120px;text-align: right;padding-right: 5px;"><label for="limitExtendCpu">'+setpythonCpu+'</label></td><td><input class="setCpu" name="limitExtendCpu" value="1"></td></tr>';
			html += '<tr><td style="width:120px;text-align: right;padding-right: 5px;"><label for="limitExtendMemory">'+setpythonMemory+'</label></td><td><input class="setMemory" name="limitExtendMemory" value="1"></td></tr>';
			html += '</table></form></div>';
		}


html += '<div id="serviceParamMonitor"><form id="resForm" style="overflow-x: auto;">';
html += '<fieldset class="tempo-fieldset" style="max-height: 156px;overflow: auto;">'+
	'<div><span class="resEventSpan" id="resMonitorLocal" style="cursor: pointer;color:#2098e6">'+TempoUtils.locale("mine.flow_res_local")+'</span> ' +
	'<span class="resEventSpan" id="resMonitorCluster" style="cursor: pointer;">'+TempoUtils.locale("mine.flow_res_cluster")+'</span>  ' +
	'<span class="resEventSpan" id="resMonitorCurrentUser" style="cursor: pointer;">'+TempoUtils.locale("mine.flow_res_curUser")+'</span> ' +
	'<span class="resEventSpan" id="resCurrentResource" style="cursor: pointer;">授权资源</span>'+
	'<a class="ui-icon tempo-ui-icon tempo-ui-icon-refresh" style="float: right;margin-right: 0px;cursor: pointer;"></a></div>'+
	'<table class="formLayout" id="resMonitorClusterTable" style="display:none"> '+
	'<tr>'+
		'<td class="formLayoutTit resTableLeft">'+

		'</td>'+
		'<td class="formLayoutTit resTableLeft">'+
		'	<label >'+TempoUtils.locale("mine.flow_res_total")+'</label>'+
		'</td>'+
		'<td class="formLayoutTit resTableLeft">'+
		'	<label >'+TempoUtils.locale("mine.flow_res_used")+'</label>'+
		'	</td>'+
		'<td class="formLayoutTit resTableLeft">'+
		'	<label >'+TempoUtils.locale("mine.flow_res_left")+'</label>'+
		'</td>'+
	'</tr>'+
	'<tr>'+
		'<td class="formLayoutTit resTableLeft">'+
		'	'+TempoUtils.locale("mine.flow_res_allCpu")+''+
		'</td>'+
		'<td class="formLayoutTit resTableLeft">'+
		'	<label ></label>'+
		'</td>'+
		'<td class="formLayoutTit resTableLeft" style="width:157px">'+
		'	<label ></label>'+
		'	</td>'+
		'<td class="formLayoutTit resTableLeft" style="width:157px">'+
		'	<label ></label>'+
		'</td>'+
	'</tr>'+
	'<tr>'+
		'<td class="formLayoutTit resTableLeft">'+
		'	'+TempoUtils.locale("mine.flow_res_allMemory")+''+
		'</td>'+
		'<td class="formLayoutTit resTableLeft">'+
		'	<label ></label>'+
		'</td>'+
		'<td class="formLayoutTit resTableLeft">'+
		'	<label ></label>'+
		'	</td>'+
		'<td class="formLayoutTit resTableLeft">'+
		'	<label ></label>'+
		'</td>'+
	'</tr>'+
	'</table>'+
	'<span id="curentUserQueueName" style="display:none;margin-bottom:15px"></span>'+
	'<table class="formLayout" id="resMonitorCurrentUserTable" style="display:none">'+
	'<tr>'+
		'<td class="formLayoutTit resTableLeft">'+

		'</td>'+
		'<td class="formLayoutTit resTableLeft">'+
		'	<label >'+TempoUtils.locale("mine.flow_res_total")+'</label>'+
		'</td>'+
		'<td class="formLayoutTit resTableLeft">'+
		'	<label >'+TempoUtils.locale("mine.flow_res_used")+'</label>'+
		'	</td>'+
		'<td class="formLayoutTit resTableLeft">'+
		'	<label >'+TempoUtils.locale("mine.flow_res_left_can_use")+'</label>'+
		'</td>'+
	'</tr>'+
	'<tr>'+
		'<td class="formLayoutTit resTableLeft">'+
		'	'+TempoUtils.locale("mine.flow_res_allCpu")+''+
		'</td>'+
		'<td class="formLayoutTit resTableLeft">'+
		'	<label ></label>'+
		'</td>'+
		'<td class="formLayoutTit resTableLeft" style="width:157px">'+
		'	<label ></label>'+
		'	</td>'+
		'<td class="formLayoutTit resTableLeft" style="width:157px">'+
		'	<label ></label>'+
		'</td>'+
	'</tr>'+
	'<tr>'+
		'<td class="formLayoutTit resTableLeft">'+
		'	'+TempoUtils.locale("mine.flow_res_allMemory")+''+
		'</td>'+
		'<td class="formLayoutTit resTableLeft">'+
		'	<label ></label>'+
		'</td>'+
		'<td class="formLayoutTit resTableLeft">'+
		'	<label ></label>'+
		'	</td>'+
		'<td class="formLayoutTit resTableLeft">'+
		'	<label ></label>'+
		'</td>'+
	'</tr>'+
	'</table>'+
	'<table class="formLayout" id="resMonitorLocalTable" >'+
	'<tr>'+
		'<td class="formLayoutTit resTableLeft">'+
		'	<label >服务器</label>'+
		'</td>'+
		'<td class="formLayoutTit resTableLeft">'+
		'	<label >' + TempoUtils.locale("mine.flow_res_resource") + '</label>'+
		'</td>'+
		'<td class="formLayoutTit resTableLeft">'+
		'	<label >'+TempoUtils.locale("mine.flow_res_total")+'</label>'+
		'</td>'+
		'<td class="formLayoutTit resTableLeft">'+
		'	<label >'+TempoUtils.locale("mine.flow_res_used")+'</label>'+
		'	</td>'+
		'<td class="formLayoutTit resTableLeft">'+
		'	<label >'+TempoUtils.locale("mine.flow_res_left")+'</label>'+
		'</td>'+
	'</tr>'+
	'<tr>'+
		'<td class="formLayoutTit resTableLeft" rowspan="2">'+
		'	<label ></label>'+
		'</td>'+
		'<td class="formLayoutTit resTableLeft">'+
		'	'+TempoUtils.locale("mine.flow_res_allCpu")+''+
		'</td>'+
		'<td class="formLayoutTit resTableLeft">'+
		'	<label ></label>'+
		'</td>'+
		'<td class="formLayoutTit resTableLeft" style="width:157px">'+
		'	<label ></label>'+
		'	</td>'+
		'<td class="formLayoutTit resTableLeft" style="width:157px">'+
		'	<label ></label>'+
		'</td>'+
	'</tr>'+
	'<tr>'+
		'<td class="formLayoutTit resTableLeft">'+
		'	'+TempoUtils.locale("mine.flow_res_allMemory")+''+
		'</td>'+
		'<td class="formLayoutTit resTableLeft">'+
		'	<label ></label>'+
		'</td>'+
		'<td class="formLayoutTit resTableLeft">'+
		'	<label ></label>'+
		'	</td>'+
		'<td class="formLayoutTit resTableLeft">'+
		'	<label ></label>'+
		'</td>'+
	'</tr>'+
	'</table>'+
	'<table class="formLayout" id="resCurrentResourceTable" style="display:none">'+
	'<tr>'+
	'<td class="formLayoutTit resTableLeft">'+

	'</td>'+
	'<td class="formLayoutTit resTableLeft">'+
	'	<label >'+TempoUtils.locale("mine.flow_res_total")+'</label>'+
	'</td>'+
	'<td class="formLayoutTit resTableLeft">'+
	'	<label >'+TempoUtils.locale("mine.flow_res_used")+'</label>'+
	'	</td>'+
	'<td class="formLayoutTit resTableLeft">'+
	'	<label >'+TempoUtils.locale("mine.flow_res_left")+'</label>'+
	'</td>'+
	'</tr>'+
	'<tr>'+
	'<td class="formLayoutTit resTableLeft">'+
	'	'+TempoUtils.locale("mine.flow_res_allCpu")+''+
	'</td>'+
	'<td class="formLayoutTit resTableLeft">'+
	'	<label ></label>'+
	'</td>'+
	'<td class="formLayoutTit resTableLeft" style="width:157px">'+
	'	<label ></label>'+
	'	</td>'+
	'<td class="formLayoutTit resTableLeft" style="width:157px">'+
	'	<label ></label>'+
	'</td>'+
	'</tr>'+
	'<tr>'+
	'<td class="formLayoutTit resTableLeft">'+
	'	'+TempoUtils.locale("mine.flow_res_allMemory")+''+
	'</td>'+
	'<td class="formLayoutTit resTableLeft">'+
	'	<label ></label>'+
	'</td>'+
	'<td class="formLayoutTit resTableLeft">'+
	'	<label ></label>'+
	'	</td>'+
	'<td class="formLayoutTit resTableLeft">'+
	'	<label ></label>'+
	'</td>'+
	'</tr>'+
	'</table>'+
	'</fieldset></form></div> </div> ';
		return html;
	}

	var parseAndFill = function(dialog,rowData){
		debugger;
		var obj = JSON.parse(rowData.flowParams).filter(function(v){if(v["$configResources$"]) return true;});
		if(obj.length > 0 ){
			var json = JSON.parse(obj[0]["$configResources$"]);
			if(Object.keys(json).length == 0){
				return false;
			}
			$(dialog.find('input[name="cpu"]')).val(json.cpu || 2);
			$(dialog.find('input[name="memory"]')).val(json.mem || 2);
			var pythonLimitParam = ajaxLoadingPythonLimit();
			$(dialog.find('input[name="limitExtendCpu"]')).val(json.limitCpu || pythonLimitParam.limitExtendCpu);
			$(dialog.find('input[name="limitExtendMemory"]')).val(json.limitMemory || pythonLimitParam.limitExtendMemory);
			var isLocal = true;
			if(json.gpu){
				dialog.find('input[name="gpu"]').closest("tr").show();
				$(dialog.find('input[name="gpu"]')).val(json.gpu||0);
			}else{
				dialog.find('input[name="gpu"]').closest("tr").hide();
			}
			if(rowData.type == "async"){
				dialog.find('select[name=mode]').closest("tr").hide();
				if(json.executors){
					dialog.find("input").closest("tr").show();
					$(dialog.find('input[name="executors"]')).val(json.executors);
					$(dialog.find('input[name="execcpu"]')).val(json.execcpu);
					$(dialog.find('input[name="execmemory"]')).val(json.execmemory);
					
					var selectCache = dialog.find('select[name=cacheconfig]');
					selectCache.closest("tr").show();
					if(!json.gpu){
						dialog.find('input[name="gpu"]').closest("tr").hide();
					}
					var values = [];
					values.push({name: "NONE",value: 'NONE'},
							{name: 'DISK_ONLY',value: 'DISK_ONLY'},
							{name: 'DISK_ONLY_2',value: 'DISK_ONLY_2'},
							{name: 'MEMORY_ONLY',value: 'MEMORY_ONLY'},
							{name: 'MEMORY_ONLY_2',value: 'MEMORY_ONLY_2'},
							{name: 'MEMORY_ONLY_SER',value: 'MEMORY_ONLY_SER'},
							{name: 'MEMORY_ONLY_SER_2',value: 'MEMORY_ONLY_SER_2'},
							{name: 'MEMORY_AND_DISK',value: 'MEMORY_AND_DISK'},
							{name: 'MEMORY_AND_DISK_2',value: 'MEMORY_AND_DISK_2'},
							{name: 'MEMORY_AND_DISK_SER',value: 'MEMORY_AND_DISK_SER'},
							{name: 'MEMORY_AND_DISK_SER_2',value: 'MEMORY_AND_DISK_SER_2'},
							{name: 'OFF_HEAP',value: 'OFF_HEAP'});
					for(var i in values) {
						var value = values[i];
						$('<option>').text(value.name).attr('value', value.value).appendTo(selectCache);
					};
					selectCache.selectmenu().selectmenu('setValue',json.cacheconfig);
					isLocal = false;
				}	
			}else{
				var mode  = json.mode || 'SYNC_ON_LOCAL';
				dialog.find('select[name=mode]').selectmenu().selectmenu('setValue', mode);
				var newModel = dialog.find('select[name=mode]').selectmenu('getValue');
				if(mode != newModel) {
					dialog.find('select[name=mode]').selectmenu('setValue', 'SYNC_ON_LOCAL');
					newModel = 'SYNC_ON_LOCAL';
				}
				if(newModel != 'SYNC_ON_LOCAL') {
					isLocal = false;
				}
			}
			if(isLocal) {
				dialog.find('label[for="driverCpu"]').text("线程数");
				dialog.find('label[for="manageMemory"]').text("内存（GB）");
			}
			return true;
		} else {
			console.error('Parse param error: ', rowData);
			dialog.find('input[name="cpu"]').val(2);
			dialog.find('input[name="memory"]').val(2);
			dialog.find('select[name=mode]').selectmenu().selectmenu('setValue', 'SYNC_ON_LOCAL');
		}
		return false;
	}
	
	var saveFlowReourcesParams = function(dialog,rowData){
		debugger
		var cpu = dialog.find('input[name=cpu]').val();
		var mem = dialog.find('input[name=memory]').val();
		var limitCpu=dialog.find('input[name=limitExtendCpu]').val();
		var limitMemory=dialog.find('input[name=limitExtendMemory]').val();
		var flow = JSON.parse(rowData.flowParams);
		var strJson = {};
		strJson.cpu = cpu;
		strJson.mem = mem;
		strJson.limitCpu = limitCpu;
		strJson.limitMemory = limitMemory;
		strJson.gpu = dialog.find('input[name=gpu]').val();
		//strJson.resourceLimitEnable=resourceLimitEnable;
		if(rowData.type == "async"){
			
			if(dialog.find('select[name=cacheconfig]').closest("tr").css("display") != "none"){
				strJson.executors = dialog.find('input[name=executors]').val();
				strJson.execcpu = dialog.find('input[name=execcpu]').val();
				strJson.execmemory = dialog.find('input[name=execmemory]').val();
				strJson.cacheconfig = dialog.find('select[name=cacheconfig]').val();
			}
		}else{ 
			var mode = dialog.find('select[name=mode]').val();
			strJson.mode = mode;
		}	
		var obj = flow.filter(function(v){if(v["$configResources$"]) return true});
		if(obj.length > 0){
			obj[0]["$configResources$"] = JSON.stringify(strJson);
		}else{
			flow.push({"$configResources$" : JSON.stringify(strJson)});
		}
		return JSON.stringify(flow);
	}
	/*************************************
	** * 以下为方便对外调用封装的函数[比如API接口]****
	************************************ */
	//初始化资源面板，包括启动参数设置和资源监控两部分
	var initResourcesPanel = function(proxy,configResources,type,serviceId){
		debugger;
		proxy.html(getResourceHtml(type));
		var resMonitorForm = proxy.find("form[id=resForm]");
		var resourceForm = proxy.find("table[id=resourcesLimit]");
		initResMonitorForm(resMonitorForm,"API");
		debugger;
		//修改ie11下单选按钮过大问题
		$("input.tempo-radio+label").css("font-size","12px");
		if("sync" == type){
            //初始化实例列表
            var instanceGrid = proxy.find('#mine-opt-instance-grid').datagrid({
				//渲染表格
				multiselect:true,
				datatype : "json",
				url : contextPath + "/api/ai/mine/getInstanceList",
				mtype : 'POST',
				height:220,
				postData:{serviceId:serviceId},
				pagination:true,
				showRefreshBth:true,
				width:550,
				colNames:[
					'IP',
					'端口',
					'最近调用时间',
					'累计次数'
				],
				colModel:[{
					name:'IP',
					editable:false,
					width:150,
				},{
					name:'PORT',
					editable:false,
					width:100,
				},{
					name:'RUNTIME',
					editable:false,
					width:150
				},{
					name:'CISHU',
					editable:false,
					width:150,
				}],
				toolbar:[{
					text:'删除实例',
					click:function(){
						debugger;
						var rowIds = TempoUtils.clone(instanceGrid.datagrid("getSelectRowIds"));
						if(!rowIds || rowIds.length <= 0){
							var msg = '请至少选择一条数据操作';
							$("<div/>").alert({
								msg:msg
							});
							return;
						}
						var ipPorts = instanceGrid.datagrid("getSelectRowData");
						var allData = instanceGrid.datagrid("getRowData");
						$.ajax({
							url: contextPath + "/api/ai/mine/deleteInstance",
							type: 'post',
							data:{serviceId:serviceId,ipPort:JSON.stringify(ipPorts)},
							async: false,
							success: function (rs) {
								var msg="服务正在停止，请稍等！";
								if(!rs.success){
									msg = rs.message;
								}
								$("<div/>").alert({
									msg:msg
								});
								proxy.find('#mine-opt-instance-grid').datagrid("reloadGrid");
								Eventbus.trigger('updateStatusLoop.service', serviceId, null, "sync");
								if(ipPorts.length == allData.length){
									// $('a.start-button').text(TempoUtils.locale("aiview.serviceStart"));
									// $("#ca-status").text(TempoUtils.locale("aiview.serviceUnStart"));
									// Eventbus.trigger('updateserviceStatus.service', TempoUtils.locale("aiview.serviceUnStart"));
									// $('a.start-button').removeClass("ui-state-disabled");
									Eventbus.trigger('flow-service-status-update.mine',"stop",false,"",25);
								}
							}
						});
					}
				},{
					text:'添加实例',
					id:'instance-add',
					click:function(){
						debugger;
						var cpu = $('#res-config input[name=cpu]').val();
						var mem = $('#res-config input[name=memory]').val();
						var limitCpu = $('#res-config input[name=limitExtendCpu]').val();
						var limitMemory = $('#res-config input[name=limitExtendMemory]').val();
						var mode = $('#res-config select[name=mode]').selectmenu('getValue');
						var requestId = "";
						if(authCodes == null || authCodes && authCodes.length == 0){
							TempoUtils.showTip(TempoUtils.locale("aiview.configtip2"));
							return ;
						}
						if (authCodes.length != 0) {
							requestId = window.btoa(authCodes[0].clientCode + "#" + authCodes[0].skCode + "#" + new Date().getTime());
						} else {
							requestId = window.btoa(new Date().getTime());
						}
						var param = {
							mode: mode || row.mode,
							cpu: cpu || 2,
							mem: mem || 2,
							limitCpu: limitCpu || 2,
							limitMemory: limitMemory || 2,
							requestId : requestId
						};
						$("#instance-add").attr("disabled","disabled");
						$.postJson({
							url: contextPath + '/api/ai/app/model/start/' + serviceId,
							data: param,
							success: function(result){
								debugger;
								$("#instance-add").removeAttr("disabled");
								var msg ="实例正在启动中，稍后请刷新实例列表！";
								if(!result.success){
									msg = result.message;
								}
								var top = $('body').height()/2-115;
								var left = $('body').width()/2-150;
								proxy.append('<div id="toolTip" tabindex="-1" role="dialog" class="ui-dialog ui-corner-all ui-widget ui-widget-content ui-front ui-dialog-buttons ui-draggable tempo-dialog tempo-alert-wrap" aria-describedby="ui-id-51" aria-labelledby="ui-id-52" style="height: auto; width: 300px; top: '+top+'px; left: '+left+'px; display: block; z-index: 135;">' +
									'<div class="ui-dialog-titlebar ui-corner-all ui-widget-header ui-helper-clearfix ui-draggable-handle">' +
									'<span id="ui-id-52" class="ui-dialog-title">提示</span>' +
									'<button type="button" id="buttondelete" class="tempo-button ui-button ui-corner-all ui-widget ui-button-icon-only ui-dialog-titlebar-close" title="" style="height: 28px; line-height: 26px;">' +
									'<span class="ui-button-icon ui-icon tempo-ui-icon tempo-ui-icon-delete"></span><span class="ui-button-icon-space"> </span></button></div>' +
									'<div class="tempo-alert ui-dialog-content ui-widget-content" id="ui-id-51" style="width: auto;min-height: 0px;max-height: none;height: 108px;padding-bottom: 0px;">' +
									'<div style="display: table; width: 100%; height: 68%;"><p>'+msg+'</p></div>'+
									'<div style="color:rgb(195,184,184)">注：若实例添加失败，请前往Hadoop管理平台查看日志。</div></div><div class="ui-dialog-buttonpane ui-widget-content ui-helper-clearfix"><div class="ui-dialog-buttonset">' +
									'<button type="button" id="buttonOK" class="tempo-button ui-button ui-corner-all ui-widget" style="height: 28px; line-height: 26px;">确定</button></div></div></div>')
								proxy.append('<div id="toolTip1" class="ui-widget-overlay ui-front" style="z-index: 101;"></div>');
								proxy.find('#buttonOK').click(function(){
									proxy.find('#toolTip').remove();
									proxy.find("#toolTip1").remove();
								})
								proxy.find('#buttondelete').click(function(){
									proxy.find('#toolTip').remove();
									proxy.find("#toolTip1").remove();
								})
								debugger;
								proxy.find('#mine-opt-instance-grid').datagrid("reloadGrid");
								Eventbus.trigger('flow-service-status-update.mine',"start",true,"",0);
							}
						})
					}
				}]
			});
            // setInterval(function(){
			// 	proxy.find('#mine-opt-instance-grid').datagrid("reloadGrid");
			// },60000)
			proxy.find('#instance-add').css("background","#5185e4").css("color","#fff").css('border','none');
			proxy.find('td[align=center]').css('display','none');
			proxy.find('td[align=right]').css('display','none');
        }
			proxy.find('#serviceParamConfig input[name!="gpu"]').numberbox({
				required: true,
				autofill:false,
				min: 1,
				precision: 0
			});
			proxy.find('#serviceParamConfig input[name="gpu"]').numberbox({
				required: true,
				autofill:false,
				min: 0,
				precision: 0
			});
			proxy.find('#resourceParamConfigTab input').numberbox({
				required: true,
				autofill:false,
				min: 1,
				precision: 0
			});
		// 优化资源加载，当点击查看资源页签得时候，再去加载，否则则整个页面打开太慢了
		var initMonitor = false;
		var initLimitResource =false;
		proxy.find("#content").tabs({
			activate: function(event, ui) {
				debugger;
				if(event.currentTarget.outerText == TempoUtils.locale("mine.sync_flow_instance")){
					proxy.find('#mine-opt-instance-grid').datagrid("reloadGrid");
				}
				if(!initMonitor) {
					ajaxLoadingResources(resMonitorForm,null,true);//初始化资源环境监控信息
					initMonitor = true;
				}
				// if(!initLimitResource) {
				// 	ajaxLoadingLimitResources(resourceForm);//初始化资源限制信息
				// 	initLimitResource = true;
				// }

			}
		});

			var ajaxLoadingLimitResources=function (resourceForm){
				$.ajax({
					url: contextPath + "/api/ai/mine/getClusterParams",
					type: 'post',
					success: function (response) {
						var result = response.data;
							var limitExtendCpu = resourceForm.find('input[name=limitExtendCpu]');
							limitExtendCpu.val(result.limitExtendCpu || 2);
							//管理python最大内存限制
							var limitExtendMemory = resourceForm.find('input[name=limitExtendMemory]');
							limitExtendMemory.val(result.limitExtendMemory || 2);

					}
				});
			}

		var selectMode = proxy.find('select[name=mode]');
		if(type == "sync" || type == "stream"){
			//同步和流时应该判断系统是否支持yarn 支持的则可以切集群
			$.ajax({
				url: contextPath + "/api/ai/mine/getClusterParams",
				type: 'post',
				async:false,
				success: function(rs) {
					var result = rs.data;
					var values = [];
					values.push({
						name: TempoUtils.locale("mine.danjimoshi"),
						value: 'SYNC_ON_LOCAL'
					});
					if(result && result.masterType.startsWith('yarn')) {
						values.push({
							name: TempoUtils.locale("mine.jiqunmoshi"),
							value: 'SYNC_ON_YARN'
						});
					};
					values.reverse();
					for(var i in values) {
						var value = values[i];
						$('<option>').text(value.name).attr('value', value.value).appendTo(selectMode);
					};
					selectMode.selectmenu({
						change: function(event, selected) {
							var val = selected.item.value;
							if("SYNC_ON_LOCAL" == val) {
								proxy.find('label[for="driverCpu"]').text("线程数");
								proxy.find('label[for="manageMemory"]').text("内存（GB）");
							} else {
								proxy.find('label[for="driverCpu"]').text("CPU个数");
								proxy.find('label[for="manageMemory"]').text("内存（GB）");
							}
						}
					});
				}
			});
		}else{
			selectMode.closest("tr").hide();
		}
		parseAndFill(proxy,{flowParams:"["+JSON.stringify(configResources)+"]",type:type});
		isOpenPythonLimit();
	}
	//初始化流程参数
	var initFlowParamGrid = function(proxy,ps){
		var width = 0;
		for (var i = 0; i < ps.length; i++) {
			// 屏蔽系统参数
			if ('system.appId' == ps[i].paramName) {
				continue;
			}
			var tr = $('<tr>').appendTo(proxy);
			var p = ps[i];
			var paramName = p.paramName;
			var paramValue = p.paramValue;
			var paramType = p.paramType;
			// 获取流程参数说明，兼容一下，以前没有置为空
			var paramDesc = "";
			if (p.paramDesc) {
				paramDesc = p.paramDesc;
			}
			var paramId = p.paramId;
			var nodeType = p.nodeType;
			var paramNameTd = $('<td>').appendTo(tr);
			var paramTypeInput = $('<input name="paramType" type="hidden">').addClass('flow_paramtype').appendTo(paramNameTd).val(paramType);
			var paramTypeInput = $('<input name="paramId" type="hidden">').addClass('flow_paramid').appendTo(paramNameTd).val(paramId);
			var paramNameInput = $('<input name="paramName">').addClass('flow_paramname').appendTo(paramNameTd).val(paramName).attr('title', paramName);
			paramNameInput.validatebox({width : 150, readonly : true, disabled: 'disabled'});
			var paramValueTd = $('<td>').appendTo(tr);
			var paramValueInput = $('<select name="paramValue">').addClass('flow_paramvalue').appendTo(paramValueTd);
			// 添加参数说明表格
			var paramDescTd = $('<td>').appendTo(tr);
			var paramDescInput = $('<input name="paramDesc">').addClass('flow_paramdesc').appendTo(paramDescTd).val(paramDesc).attr('title', paramDesc);
			// 如果是第一次进入，修改值，以后都使用同一个值
			if(width == 0) {
				width = proxy.width() - 425;
			}
			paramDescInput.validatebox({width : width, readonly : true, disabled: 'disabled'});

			paramNameInput.attr('title', paramName);
			getFlowParams(paramType, paramValueInput, paramValue, nodeType,false);//初始化时禁用掉
			// 参数说明 值回显
			paramDescInput.attr('title', paramDesc);
		}
	}
	var saveResourcesPanel = function(proxy,flowParams,type){
		if(proxy.find('form').formValidate()) {
			return saveFlowReourcesParams(proxy,{flowParams:JSON.stringify(flowParams),type:type});
		}
	}
	//保存流程参数和资源面板的启动参数设置，并返回结果
	var saveFlowParamGrid = function(proxy,proxy1,row){
		debugger;
		var currentFlowParams = [];
		var paramsLine = proxy.find('tbody tr');
		paramsLine.each(function(i,v){
			if($(v).find("input.flow_paramname").length == 0){
				return;
			}
			var paramName = $(v).find('input.flow_paramname').val();
			var paramValue =  $(v).find('select.flow_paramvalue').selectmenu('getValue');
			var paramType =  $(v).find('input.flow_paramtype').val();
			var paramId =  $(v).find('input.flow_paramid').val();
			// 获取参数说明的值
			var paramDesc =  $(v).find('input.flow_paramdesc').val();
			var param = {};
			param.paramName = paramName;
			param.paramValue = paramValue;
			param.paramId = paramId;
			param.paramType = paramType;
			param.paramDesc = paramDesc;
			if(!$.isEmptyObject(param)){
				currentFlowParams.push(param);
			}
		});
		
		var rs = saveResourcesPanel(proxy1,currentFlowParams,row.type);
		row.flowParams = rs;
	}
	var saveApiServiceConfig = function(row,isEdit,callback){
		debugger
		var rowNew = TempoUtils.clone(row);
		if(!rowNew.flowid){
			$("<div/>").alert({msg : TempoUtils.locale("mine.publish-job-none"), height : 180});
			return;
		}
		var url = isEdit ? contextPath + '/api/ai/mine/publish/updateService' : contextPath + '/api/ai/mine/publish/saveService';
		var process = $("<div/>").tempoprogressbar();
		
		delete rowNew.ignore
		$.ajax({
			url : url,
			type : 'post',
			data : JSON.stringify(rowNew),
			contentType : 'application/json',
			success : function(obj) {
				process.tempoprogressbar("destroy");
				if(callback) callback(obj);
				if(window.location.href.indexOf("view/outcome") != -1) {
					$("#ca-name").text(TempoMineUtils.decodeHTML(row.name));
				}
			}
		});
	}

	var requestToken = function(appId, doneFunc, successFunc) {
		$.ajax({
			url: contextPath + "/api/ai/mine/webapi/gen-token",
			type: 'POST',
			data: {id: appId},
			success: function(result) {
				debugger
				doneFunc(result);
				if(result.success) {
					successFunc(result.data);
				} else {
					$("<div/>").alert({msg : "获取API访问token失败", height : 180});
				}
			}
		})
	};

	/**
	 * 初始化资源使用情况监控页面
	 * @param $resource 资源使用情况的块div，该div的内部布局必须是有头和身体，头部放置刷新按钮和title，身体放置表格的div
	 * @param resourceGrid 表格的div
	 */
	var initResourceMonitor = function($resource, resourceGrid) {
		/**
		 * 初始化资源监控的html
		 * @returns {string} html
		 */
		var getResourceMonitorHtml = function () {
			var html ="<div id='content'> " +
				"<ul id='ul'>" +
				"<li><a href=\"#res-local\"><span>"+TempoUtils.locale("mine.flow_res_local")+"</span></a></li>"+
				"<li><a href=\"#res-cluster\"><span>"+TempoUtils.locale("mine.flow_res_cluster")+"</span></a></li>"+
				"<li><a href=\"#res-curUser\"><span>"+TempoUtils.locale("mine.flow_res_curUser")+"</span></a></li>"+
				"<li><a href=\"#res-monitor\"><span>授权资源</span></a></li>"+
				"</ul>"+
				'<div id="res-local">'+
				'<table class="formLayout" id="resMonitorLocalTable" >'+
				'<tr>'+
				'<td class="formLayoutTit resTableLeft">'+
				'    <label >服务器</label>'+
				'</td>'+
				'<td class="formLayoutTit resTableLeft">'+
				'	<label >' + TempoUtils.locale("mine.flow_res_resource") + '</label>'+
				'</td>'+
				'<td class="formLayoutTit resTableLeft">'+
				'	<label >'+TempoUtils.locale("mine.flow_res_total")+'</label>'+
				'</td>'+
				'<td class="formLayoutTit resTableLeft">'+
				'	<label >'+TempoUtils.locale("mine.flow_res_used")+'</label>'+
				'	</td>'+
				'<td class="formLayoutTit resTableLeft">'+
				'	<label >'+TempoUtils.locale("mine.flow_res_left")+'</label>'+
				'</td>'+
				'</tr>'+
				'<tr>'+
				'<td class="formLayoutTit resTableLeft" rowspan="2">'+
				'	<label ></label>'+
				'</td>'+
				'<td class="formLayoutTit resTableLeft">'+
				'	'+TempoUtils.locale("mine.flow_res_allCpu")+''+
				'</td>'+
				'<td class="formLayoutTit resTableLeft">'+
				'	<label ></label>'+
				'</td>'+
				'<td class="formLayoutTit resTableLeft" >'+
				'	<label ></label>'+
				'	</td>'+
				'<td class="formLayoutTit resTableLeft" >'+
				'	<label ></label>'+
				'</td>'+
				'</tr>'+
				'<tr>'+
				'<td class="formLayoutTit resTableLeft">'+
				'	'+TempoUtils.locale("mine.flow_res_allMemory")+''+
				'</td>'+
				'<td class="formLayoutTit resTableLeft">'+
				'	<label ></label>'+
				'</td>'+
				'<td class="formLayoutTit resTableLeft">'+
				'	<label ></label>'+
				'	</td>'+
				'<td class="formLayoutTit resTableLeft">'+
				'	<label ></label>'+
				'</td>'+
				'</tr>'+
				'</table>'+
				'</div>'+
				'<div id="res-cluster">' +
				'<table class="formLayout" id="resMonitorClusterTable"> '+
				'<tr>'+
				'<td class="formLayoutTit resTableLeft">'+
				'</td>'+
				'<td class="formLayoutTit resTableLeft">'+
				'	<label >'+TempoUtils.locale("mine.flow_res_total")+'</label>'+
				'</td>'+
				'<td class="formLayoutTit resTableLeft">'+
				'	<label >'+TempoUtils.locale("mine.flow_res_used")+'</label>'+
				'</td>'+
				'<td class="formLayoutTit resTableLeft">'+
				'	<label >'+TempoUtils.locale("mine.flow_res_left")+'</label>'+
				'</td>'+
				'</tr>'+
				'<tr>'+
				'<td class="formLayoutTit resTableLeft">'+
				'	'+TempoUtils.locale("mine.flow_res_allCpu")+''+
				'</td>'+
				'<td class="formLayoutTit resTableLeft">'+
				'	<label ></label>'+
				'</td>'+
				'<td class="formLayoutTit resTableLeft">'+
				'	<label ></label>'+
				'	</td>'+
				'<td class="formLayoutTit resTableLeft">'+
				'	<label ></label>'+
				'</td>'+
				'</tr>'+
				'<tr>'+
				'<td class="formLayoutTit resTableLeft">'+
				'	'+TempoUtils.locale("mine.flow_res_allMemory")+''+
				'</td>'+
				'<td class="formLayoutTit resTableLeft">'+
				'	<label ></label>'+
				'</td>'+
				'<td class="formLayoutTit resTableLeft">'+
				'	<label ></label>'+
				'	</td>'+
				'<td class="formLayoutTit resTableLeft">'+
				'	<label ></label>'+
				'</td>'+
				'</tr>'+
				'</table>'+
				'</div>'+
				'<div id="res-curUser">' +
				'<table class="formLayout" id="resMonitorCurrentUserTable">'+
				'<tr>'+
				'<td class="formLayoutTit resTableLeft">'+

				'</td>'+
				'<td class="formLayoutTit resTableLeft">'+
				'	<label >'+TempoUtils.locale("mine.flow_res_total")+'</label>'+
				'</td>'+
				'<td class="formLayoutTit resTableLeft">'+
				'	<label >'+TempoUtils.locale("mine.flow_res_used")+'</label>'+
				'	</td>'+
				'<td class="formLayoutTit resTableLeft">'+
				'	<label >'+TempoUtils.locale("mine.flow_res_left_can_use")+'</label>'+
				'</td>'+
				'</tr>'+
				'<tr>'+
				'<td class="formLayoutTit resTableLeft">'+
				'	'+TempoUtils.locale("mine.flow_res_allCpu")+''+
				'</td>'+
				'<td class="formLayoutTit resTableLeft">'+
				'	<label ></label>'+
				'</td>'+
				'<td class="formLayoutTit resTableLeft">'+
				'	<label ></label>'+
				'	</td>'+
				'<td class="formLayoutTit resTableLeft">'+
				'	<label ></label>'+
				'</td>'+
				'</tr>'+
				'<tr>'+
				'<td class="formLayoutTit resTableLeft">'+
				'	'+TempoUtils.locale("mine.flow_res_allMemory")+''+
				'</td>'+
				'<td class="formLayoutTit resTableLeft">'+
				'	<label ></label>'+
				'</td>'+
				'<td class="formLayoutTit resTableLeft">'+
				'	<label ></label>'+
				'	</td>'+
				'<td class="formLayoutTit resTableLeft">'+
				'	<label ></label>'+
				'</td>'+
				'</tr>'+
				'</table>'+
				'</div>'+
				'<div id="res-monitor">'+
				'<table class="formLayout" id="resCurrentResourceTable">'+
				'<tr>'+
				'<td class="formLayoutTit resTableLeft">'+
				'</td>'+
				'<td class="formLayoutTit resTableLeft">'+
				'	<label >'+TempoUtils.locale("mine.flow_res_total")+'</label>'+
				'</td>'+
				'<td class="formLayoutTit resTableLeft">'+
				'	<label >'+TempoUtils.locale("mine.flow_res_used")+'</label>'+
				'	</td>'+
				'<td class="formLayoutTit resTableLeft">'+
				'	<label >'+TempoUtils.locale("mine.flow_res_left")+'</label>'+
				'</td>'+
				'</tr>'+
				'<tr>'+
				'<td class="formLayoutTit resTableLeft">'+
				'	'+TempoUtils.locale("mine.flow_res_allCpu")+''+
				'</td>'+
				'<td class="formLayoutTit resTableLeft">'+
				'	<label ></label>'+
				'</td>'+
				'<td class="formLayoutTit resTableLeft">'+
				'	<label ></label>'+
				'	</td>'+
				'<td class="formLayoutTit resTableLeft">'+
				'	<label ></label>'+
				'</td>'+
				'</tr>'+
				'<tr>'+
				'<td class="formLayoutTit resTableLeft">'+
				'	'+TempoUtils.locale("mine.flow_res_allMemory")+''+
				'</td>'+
				'<td class="formLayoutTit resTableLeft">'+
				'	<label ></label>'+
				'</td>'+
				'<td class="formLayoutTit resTableLeft">'+
				'	<label ></label>'+
				'	</td>'+
				'<td class="formLayoutTit resTableLeft">'+
				'	<label ></label>'+
				'</td>'+
				'</tr>'+
				'</table>'+
				'</div>'+
				'</div>';
			return html;
		};

		/**
		 * 初始化资源监控页面
		 * @param resourceGrid
		 */
		var initResourceMonitorPage = function(resourceGrid){
			resourceGrid.html(getResourceMonitorHtml());

			resourceGrid.find("table td").css("border","1px solid #dddddd").css("text-align","center ");
			resourceGrid.find("table tr:nth-child(1) td").css("color","#5b6e85").css("font-weight","bold")
				.css("border-top","1px solid #dae0e9").css("border-bottom","2px solid #dae0e9").css("line-height","23px");
			resourceGrid.find("table tr:nth-child(3)").css("background","#f8fafd");

			resourceGrid.find("#content").tabs({
				activate: function(event, ui) {
				}
			});
			debugger;
			ajaxLoadingResources(resourceGrid,null,false);//初始化资源环境监控信息
		};

		/**
		 * 绑定资源监控事件
		 * @param $resource
		 * @param resourceGrid
		 */
		var bindResourceMonitorEvent = function($resource, resourceGrid) {
			$resource.find(".tempo-ui-icon-refresh").unbind("click").bind("click", function () {
				ajaxLoadingResources(resourceGrid, null, true)
			});
		};

		initResourceMonitorPage(resourceGrid);
		bindResourceMonitorEvent($resource, resourceGrid);
	};

	// 绑定事件，供外部调用
	Eventbus.one('testSyncConfigFlow.mine', testSyncConfigFlow);
	Eventbus.one('testAsyncConfigFlow.mine', testAsyncConfigFlow);
	Eventbus.one('testSyncFlow.mine', testSyncFlow);
	Eventbus.one('testAsyncFlow.mine', testAsyncFlow);
	Eventbus.one("initResourcesPanel.mine",initResourcesPanel);//初始化资源面板，包括启动参数设置和资源监控两部分
	Eventbus.one("initFlowParamGrid.mine",initFlowParamGrid);//初始化流程参数
	Eventbus.one("saveFlowParamGrid.mine",saveFlowParamGrid);//保存流程参数和资源面板的启动参数设置，并返回拼接结果
	Eventbus.one("saveApiServiceConfig.mine",saveApiServiceConfig);//为API提供一个单纯保存的方法

	Eventbus.one("initResourceMonitor.mine", initResourceMonitor);//初始化资源使用情况监控
}
window.MinePublishServiceController = MinePublishServiceController;